且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为所有 Flask 路由添加前缀

更新时间:2023-12-01 10:23:52

答案取决于您如何为该应用程序提供服务.

The answer depends on how you are serving this application.

假设您要在 WSGI 容器(mod_wsgi、uwsgi、gunicorn 等)中运行此应用程序;您需要实际挂载,在该前缀应用程序作为该 WSGI 容器的子部分(任何使用 WSGI 的东西都可以)并设置您的 APPLICATION_ROOT 配置值到您的前缀:

Assuming that you are going to run this application inside of a WSGI container (mod_wsgi, uwsgi, gunicorn, etc); you need to actually mount, at that prefix the application as a sub-part of that WSGI container (anything that speaks WSGI will do) and to set your APPLICATION_ROOT config value to your prefix:

app.config["APPLICATION_ROOT"] = "/abc/123"

@app.route("/")
def index():
    return "The URL for this page is {}".format(url_for("index"))

# Will return "The URL for this page is /abc/123/"

设置 APPLICATION_ROOT 配置value 只是将 Flask 的会话 cookie 限制为该 URL 前缀.Flask 和 Werkzeug 出色的 WSGI 处理能力会自动为您处理其他一切.

Setting the APPLICATION_ROOT config value simply limit Flask's session cookie to that URL prefix. Everything else will be automatically handled for you by Flask and Werkzeug's excellent WSGI handling capabilities.

如果您不确定第一段的意思,请看一下这个安装了 Flask 的示例应用程序:

If you are not sure what the first paragraph means, take a look at this example application with Flask mounted inside of it:

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

app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/abc/123'

@app.route('/')
def index():
    return 'The URL for this page is {}'.format(url_for('index'))

def simple(env, resp):
    resp(b'200 OK', [(b'Content-Type', b'text/plain')])
    return [b'Hello WSGI World']

app.wsgi_app = DispatcherMiddleware(simple, {'/abc/123': app.wsgi_app})

if __name__ == '__main__':
    app.run('localhost', 5000)

代理对应用的请求

另一方面,如果您将在其 WSGI 容器的根目录运行 Flask 应用程序并向其代理请求(例如,如果它是 FastCGI,或者如果 nginx 是 proxy_pass-ing 向您的独立 uwsgi/gevent 服务器请求子端点,然后您可以:

Proxying requests to the app

If, on the other hand, you will be running your Flask application at the root of its WSGI container and proxying requests to it (for example, if it's being FastCGI'd to, or if nginx is proxy_pass-ing requests for a sub-endpoint to your stand-alone uwsgi / gevent server then you can either:

  • 使用蓝图,正如 Miguel 在他的回答中指出的那样.
  • 使用来自 werkzeugDispatcherMiddleware(或来自 su27 的答案) 将您的应用程序安装在您正在使用的独立 WSGI 服务器中.(有关要使用的代码,请参阅正确子挂载您的应用的示例以上).
  • Use a Blueprint, as Miguel points out in his answer.
  • or use the DispatcherMiddleware from werkzeug (or the PrefixMiddleware from su27's answer) to sub-mount your application in the stand-alone WSGI server you're using. (See An example of properly sub-mounting your app above for the code to use).