小编典典

为所有Flask路线添加前缀

flask

我有一个前缀要添加到每条路线。现在,我在每个定义处都向路线添加了一个常量。有没有一种方法可以自动执行此操作?

PREFIX = "/abc/123"

@app.route(PREFIX + "/")
def index_page():
  return "This is a website about burritos"

@app.route(PREFIX + "/about")
def about_page():
  return "This is a website about burritos"

阅读 1210

收藏
2020-04-04

共2个答案

小编典典

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

安装在另一个WSGI容器中
假设你将在WSGI容器(mod_wsgi,uwsgi,gunicorn等)中运行此应用程序;你实际上需要将该应用程序作为该WSGI容器的子部分挂载在该前缀处(任何讲WSGI的东西都可以使用),并将APPLICATION_ROOTconfig值设置为你的前缀:

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配置值只是将Flask的会话cookie限制为该URL前缀。Flask和Werkzeug出色的WSGI处理功能将自动为你处理其他所有事情。

正确重新安装你的应用程序的示例
如果不确定第一段的含义,请看一下其中装有Flask的示例应用程序:

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)

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

  • 正如Miguel在回答中指出的那样,使用蓝图。
  • 或者使用DispatcherMiddleware从werkzeug(或PrefixMiddleware从SU27的答案)到副安装在你使用的独立WSGI服务器应用程序。(请参阅上面的示例,正​​确地重新安装你的应用以获取使用的代码)。
2020-04-04
小编典典

你可以将路线设置为蓝图:

bp = Blueprint('burritos', __name__,
                        template_folder='templates')

@bp.route("/")
def index_page():
  return "This is a website about burritos"

@bp.route("/about")
def about_page():
  return "This is a website about burritos"

然后,你使用前缀将蓝图注册到应用程序:

app = Flask(__name__)
app.register_blueprint(bp, url_prefix='/abc/123')
2020-04-04