关于python:带有尾随斜杠的Flask POST

Flask POSTs with Trailing Slash

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

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

这样,客户就可以获得相同的结果。

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

1
2
3
4
5
6
7
8
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一起失败;如果您是在调试模式下运行,它将失败,并发出以下通知:

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

而且,你甚至不能这样做:

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

或者:

1
2
3
4
5
6
7
@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同时处理非尾随斜杠和尾随斜杠?


请参阅本帖:尾随斜线在烧瓶路径规则中触发404

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

全球地:

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

…或每路线

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

您也可以检查此链接。关于这个问题,Github有单独的讨论。https://github.com/pallets/flask/issues/1783(货盘/烧瓶/问题)


您可以检查request.path是否为/foo/,然后将其重定向到您想要的位置:

1
2
3
4
5
6
7
8
9
10
11
@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