【问题标题】:How can I use a dispatcher middleware on flask?如何在烧瓶上使用调度程序中间件?
【发布时间】:2019-07-18 09:58:44
【问题描述】:

我正在尝试使用 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 上运行时,但是当我在该网址上导航时,我得到了404 响应。仅在导航到页面http://127.0.0.1:5000/home 时有效。有人可以帮我理解为什么会这样吗?感谢您提供的任何帮助

【问题讨论】:

标签: python flask middleware wsgi


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答!不过我想使用应用程序调度程序,因为我想让许多应用程序相互连接
【解决方案2】:

解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2020-10-20
    相关资源
    最近更新 更多