1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| from werkzeug.wsgi import DispatcherMiddleware from werkzeug.serving import run_simple from flask import Flask from werkzeug.middleware.dispatcher import DispatcherMiddleware
app1 = Flask("app01") app2 = Flask("app02")
@app1.route('/index1') def index(): return "axba"
@app2.route('/index2') def index(): return "hello"
app = DispatcherMiddleware(app1, { "/sec": app2, })
if __name__ == '__main__': run_simple('localhost', 5000, app)
用户请求进来,调用Dispatch中间件的__call__,进行app选择,并封装environ然后执行对应app.__call__(environ, start_response) def __call__(self, environ, start_response): script = environ.get("PATH_INFO", "") path_info = ""
while "/" in script: if script in self.mounts: app = self.mounts[script] break
script, last_item = script.rsplit("/", 1) path_info = "/%s%s" % (last_item, path_info) else: 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)
|