gpt4 book ai didi

python - 带有尾部斜杠的 Flask POST

转载 作者:太空狗 更新时间:2023-10-30 00:59:21 25 4
gpt4 key购买 nike

文档指出定义路由的首选方法是包含一个尾部斜杠:

@app.route('/foo/', methods=['GET'])
def get_foo():
pass

这样,客户端可以GET/fooGET/foo/ 并收到相同的结果。

但是,POST 方法没有相同的行为。

from flask import Flaskapp = Flask(__name__)@app.route('/foo/', methods=['POST'])def post_foo():    return "bar"app.run(port=5000)

Here, if you POST /foo, it will fail with method not allowed if you are not running in debug mode, or it will fail with the following notice if you are in debug mode:

A request was sent to this URL (http://localhost:5000/foo) but a redirect was issued automatically by the routing system to "http://localhost:5000/foo/". The URL was defined with a trailing slash so Flask will automatically redirect to the URL with the trailing slash if it was accessed without one. Make sure to directly send your POST-request to this URL since we can't make browsers or HTTP clients redirect with form data reliably or without user interaction


Moreover, it appears that you cannot even do this:

@app.route('/foo', methods=['POST'])
@app.route('/foo/', methods=['POST'])
def post_foo():
return "bar"

或者这个:

@app.route('/foo', methods=['POST'])def post_foo_no_slash():    return redirect(url_for('post_foo'), code=302)@app.route('/foo/', methods=['POST'])def post_foo():    return "bar"

有什么方法可以让 POST 同时处理非尾随斜杠和尾随斜杠吗?

最佳答案

请引用这篇文章: Trailing slash triggers 404 in Flask path rule

您可以禁用严格的斜杠来支持您的需求

全局:

app = Flask(__name__)
app.url_map.strict_slashes = False

...或每条路线

@app.route('/foo', methods=['POST'], strict_slashes=False)
def foo():
return 'foo'

您也可以查看此链接。关于这个在github上有单独的讨论。 https://github.com/pallets/flask/issues/1783

关于python - 带有尾部斜杠的 Flask POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42661277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com