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

Posted Lift is short, You need Python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask快速入门(20) — 多app应用相关的知识,希望对你有一定的参考价值。

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)

以上是关于Flask快速入门(20) — 多app应用的主要内容,如果未能解决你的问题,请参考以下文章

flask-带你快速入门

python flask 基础入门

Flask之快速入门

flask快速入门

Flask快速入门 — flask路由的本质

二 Flask快速入门