Flask快速入门(20) — 多app应用

时间:2023-01-26 18:47:27

Flask快速入门(20) — 多app应用

之前一直是一个app,如果有多个app该怎么进行分发呢?

from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.serving import run_simple
from flask import Flask,current_app

# 注册两个app
app1 = Flask('app01')
app2 = Flask('app02')

@app1.route('/index')
def index():
    return 'app01'

@app2.route('/index')
def index():
    return 'app02'

dm = DispatcherMiddleware(app1,{
    '/sec':app2,
})
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/index;此时获取到的script为‘/sec/index’
    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)