如何在 Flask 上使用调度程序中间件?

How can I use a dispatcher middleware on flask?

我正在尝试使用 wsgi DispatcherMiddleware 以便在我的申请中添加 url 前缀。我为调度程序编写了一个模块,为应用程序编写了一个模块,它只有一个名为 home 的视图,这是提供主页的地方。

这是我的app1.py

import flask
from flask import request, jsonify

app = flask.Flask(__name__)
app.config["DEBUG"] = True


@app.route('/home', methods=['GET'])
def home():
    return "<h1>Home</h1>"

dispatcher.py

from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.exceptions import NotFound

from app1 import app


app = Flask(__name__)

app.wsgi_app = DispatcherMiddleware(NotFound(), {
    "/prefix": app
})

if __name__ == "__main__":
    app.run()

我想做的是能够导航到 http://127.0.0.1:5000/prefix/home 当我 运行 在控制台 py dispatcher.py 上时,但是当我在那个 url 上导航时,我得到了 404 响应。仅在页面导航中有效http://127.0.0.1:5000/home。有人可以帮我理解为什么会这样吗?感谢您提供的任何帮助

如果您选择使用蓝图,为所有路由添加前缀非常简单

https://flask.palletsprojects.com/en/1.0.x/tutorial/views/#create-a-blueprint

from flask import Flask, Blueprint

app = Flask(__name__)
prefixed = Blueprint('prefixed', __name__, url_prefix='/prefixed')

@app.route('/nonprefixed')
def non_prefixed_route():
    return 'this is the nonprefixed route'

@prefixed.route('/route')
def some_route():
    return 'this is the prefixed route'


app.register_blueprint(prefixed)
if __name__ == "__main__":
    app.run()

正在测试路线:

> curl localhost:5000/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>

> curl localhost:5000/nonprefixed
this is the nonprefixed route

> curl localhost:5000/prefixed/route
this is the prefixed route

解决方案:

我用错了 dispacherapp1 的相同名称。

dispacher.py应编辑如下:

from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from werkzeug.exceptions import NotFound

from app1 import app as app1


app = Flask(__name__)

app.wsgi_app = DispatcherMiddleware(NotFound(), {
    "/prefix": app1
})

if __name__ == "__main__":
    app.run()