与尾随瓶的POST斜线

与尾随瓶的POST斜线

问题描述:

文档状态来定义路由的首选方法是,包括一个尾随斜线:与尾随瓶的POST斜线

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

这种方式,客户端可以GET /fooGET /foo/和接收相同的结果。

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

 
from flask import Flask 
app = Flask(__name__) 

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

app.run(port=5000) 

在这里,如果你POST /foo,它将如果你是不是在调试模式下运行失败,method not allowed,或者如果你是在调试模式下,它会用以下通知失败:

请求被发送到这个URL(http://localhost:5000/foo),但重定向由路由系统自动发布到" http://localhost:5000/foo/"。 URL是使用尾部斜线定义的,因此如果没有访问它,Flask将自动重定向到带有斜杠的URL。请务必直接发送您的POST请求到这个网址,因为我们不能让浏览器或HTTP客户端表单数据重定向可靠或没有用户交互


而且,看来,你甚至不能做到这一点:

@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在非尾随斜线和尾随斜线上工作?

您可以检查request.path是否/foo/与否然后重定向它到你想去的地方:

@app.before_request 
def before_request(): 
    if request.path == '/foo': 
     return redirect(url_for('foo'), code=123) 

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

$ http post localhost:5000/foo 
127.0.0.1 - - [08/Mar/2017 13:06:48] "POST /foo HTTP/1.1" 123 

请参考这个帖子: 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