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

时间:2019-07-18 09:58:44

标签: python flask middleware wsgi

我正在尝试使用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时有效。有人可以帮我理解为什么会这样吗?感谢您能提供的任何帮助

2 个答案:

答案 0 :(得分:0)

如果您选择使用“蓝图”,则在所有路由中添加前缀确实非常简单

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

答案 1 :(得分:0)

解决方案:

我在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()