首页 文章

带有尾随斜杠的Flask POST

提问于
浏览
4

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

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

这样,客户端可以 GET /fooGET /foo/ 并获得相同的结果 .

但是,POSTed方法没有相同的行为 .

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请求发送到此URL,因为我们无法使浏览器或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 同时处理非尾随斜杠和尾随斜杠?

2 回答

  • 0

    请参考这篇文章: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

  • 3

    您可以检查 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
    

相关问题