应用程序调度¶
应用程序调度是在 WSGI 级别合并多个 Flask 应用程序的过程。你不仅可以合并 Flask 应用程序,还可以合并任何 WSGI 应用程序。这将允许你在同一个解释器中并排运行 Django 和 Flask 应用程序(如果你愿意)。它的实用性取决于应用程序在内部如何工作。
与 大型应用程序作为包 的根本区别在于,在这种情况下,你正在运行完全彼此隔离的相同或不同的 Flask 应用程序。它们运行不同的配置,并在 WSGI 级别进行调度。
使用此文档¶
以下每种技术和示例都会生成一个 application
对象,该对象可以使用任何 WSGI 服务器运行。对于开发,使用 flask run
命令启动开发服务器。对于生产,请参阅 部署到生产。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
合并应用程序¶
如果你有完全分离的应用程序,并且希望它们在同一个 Python 解释器进程中并排工作,则可以利用 werkzeug.wsgi.DispatcherMiddleware
。这里的想法是,每个 Flask 应用程序都是一个有效的 WSGI 应用程序,它们被调度中间件合并到一个更大的应用程序中,该应用程序基于前缀进行调度。
例如,你可以让你的主应用程序在 /
上运行,你的后端界面在 /backend
上运行。
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from frontend_app import application as frontend
from backend_app import application as backend
application = DispatcherMiddleware(frontend, {
'/backend': backend
})
按子域调度¶
有时你可能希望使用具有不同配置的同一应用程序的多个实例。假设应用程序是在函数内部创建的,并且你可以调用该函数对其进行实例化,那么这很容易实现。为了开发你的应用程序以支持在函数中创建新实例,请查看 应用程序工厂 模式。
一个非常常见的示例是为每个子域创建应用程序。例如,你将 Web 服务器配置为将所有子域的所有请求调度到你的应用程序,然后使用子域信息创建特定于用户的实例。一旦设置服务器侦听所有子域,就可以使用非常简单的 WSGI 应用程序来执行动态应用程序创建。
在这方面抽象的完美级别是 WSGI 层。编写自己的 WSGI 应用程序,该应用程序查看传入的请求并将其委托给你的 Flask 应用程序。如果该应用程序尚不存在,则会动态创建并记住它。
from threading import Lock
class SubdomainDispatcher:
def __init__(self, domain, create_app):
self.domain = domain
self.create_app = create_app
self.lock = Lock()
self.instances = {}
def get_application(self, host):
host = host.split(':')[0]
assert host.endswith(self.domain), 'Configuration error'
subdomain = host[:-len(self.domain)].rstrip('.')
with self.lock:
app = self.instances.get(subdomain)
if app is None:
app = self.create_app(subdomain)
self.instances[subdomain] = app
return app
def __call__(self, environ, start_response):
app = self.get_application(environ['HTTP_HOST'])
return app(environ, start_response)
然后可以这样使用此分派器
from myapplication import create_app, get_user_for_subdomain
from werkzeug.exceptions import NotFound
def make_app(subdomain):
user = get_user_for_subdomain(subdomain)
if user is None:
# if there is no user for that subdomain we still have
# to return a WSGI application that handles that request.
# We can then just return the NotFound() exception as
# application which will render a default 404 page.
# You might also redirect the user to the main page then
return NotFound()
# otherwise create the application for the specific user
return create_app(user)
application = SubdomainDispatcher('example.com', make_app)
按路径分派¶
按 URL 上的路径分派非常相似。只需查看请求路径直到第一个斜杠,而不是查看 Host
头部来找出子域。
from threading import Lock
from wsgiref.util import shift_path_info
class PathDispatcher:
def __init__(self, default_app, create_app):
self.default_app = default_app
self.create_app = create_app
self.lock = Lock()
self.instances = {}
def get_application(self, prefix):
with self.lock:
app = self.instances.get(prefix)
if app is None:
app = self.create_app(prefix)
if app is not None:
self.instances[prefix] = app
return app
def __call__(self, environ, start_response):
app = self.get_application(_peek_path_info(environ))
if app is not None:
shift_path_info(environ)
else:
app = self.default_app
return app(environ, start_response)
def _peek_path_info(environ):
segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1)
if segments:
return segments[0]
return None
此方法与子域方法之间的主要区别在于,如果创建器函数返回 None
,此方法将回退到另一个应用程序。
from myapplication import create_app, default_app, get_user_for_prefix
def make_app(prefix):
user = get_user_for_prefix(prefix)
if user is not None:
return create_app(user)
application = PathDispatcher(default_app, make_app)