- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
文档指出定义路由的首选方法是包含一个尾部斜杠:
@app.route('/foo/', methods=['GET'])
def get_foo():
pass
这样,客户端可以GET/foo
或GET/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/
我是一名优秀的程序员,十分优秀!