共计 1436 个字符,预计需要花费 4 分钟才能阅读完成。
多 app 应用(应用少了解即可)
请求来时, 通过不同的 url 交给不同的 APP 进行处理 (一般使用蓝图实现)
- 需要导入
DispatcherMiddleware
这个类 1.0
版本之前导入方式:
from werkzeug.wsgi import DispatcherMiddleware
1.0
版本后上面导入方式被弃用, 使用新的导入方式
werkzeug.middleware.dispatcher import DispatcherMiddleware
- 使用 :
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.serving import run_simple
from flask import Flask, current_app
app01 = Flask('app01')
app02 = Flask('app02')
@app01.route('/index1')
def index1(): # http://localhost:5000/index1
return 'app01'
@app02.route('/index2')
def index2(): # http://localhost:5000/sec/index2
return 'app02'
# 第一个参数传入一个 app, 第二个参数掺入一个字典:{" 前缀 ":app}
dm = DispatcherMiddleware(app01, {'/sec': app02})
if __name__ == '__main__':
run_simple('localhost', 5000, dm)
源码分析
dm
是DispatcherMiddleware
对象,dm+()
触发的是该类的__call__()
方法
# dm = DispatcherMiddleware(app1,{'/sec':app2})
def __init__(self, app, mounts=None):
self.app = app
self.mounts = mounts or {}
def __call__(self, environ, start_response):
script = environ.get("PATH_INFO", "") # 获取 url 信息,如 url 为 http://127.0.0.1:5000/sec/index2; 此时获取到的 script 为‘/sec/index2’path_info = ""
while "/" in script:
# 此时 self.mounts = {'/sec':app2}
if script in self.mounts:
app = self.mounts[script]
break
script, last_item = script.rsplit("/", 1) # 循环从右边以 / 切分 1 次,给 script 重新赋值
path_info = "/%s%s" % (last_item, path_info)
else:
# 如果没有匹配上,app = app1,如果匹配上了 app = self.mounts[script] 即 app2
app = self.mounts.get(script, self.app)
original_script_name = environ.get("SCRIPT_NAME", "")
environ["SCRIPT_NAME"] = original_script_name + script
environ["PATH_INFO"] = path_info
return app(environ, start_response)
正文完