烧瓶重定向(相同的路由,不同的HTTP方法)最终在302循环中结束

时间:2020-02-24 09:57:09

标签: python flask

我正在尝试从PUT重定向到GET请求,由于request.method似乎在所有情况下都设置为PUT,因此我最终陷入302循环时间。我尝试将_method='GET'添加到url_for函数中。

@app.route('/test', methods=['GET', 'PUT'])
def test_route():
    if request.method == 'PUT':
        ...
        return redirect(url_for('app.test_route'))
    else:
        return render_template('test.html')

结果是:

[2020-02-24 04:44:06,093] INFO in _internal: 127.0.0.1 - - [24/Feb/2020 04:44:06] "PUT /test HTTP/1.1" 302 -
[2020-02-24 04:44:06,207] INFO in _internal: 127.0.0.1 - - [24/Feb/2020 04:44:06] "PUT /test HTTP/1.1" 302 -
[2020-02-24 04:44:06,331] INFO in _internal: 127.0.0.1 - - [24/Feb/2020 04:44:06] "PUT /test HTTP/1.1" 302 -
[2020-02-24 04:44:06,468] INFO in _internal: 127.0.0.1 - - [24/Feb/2020 04:44:06] "PUT /test HTTP/1.1" 302 -
[2020-02-24 04:44:06,567] INFO in _internal: 127.0.0.1 - - [24/Feb/2020 04:44:06] "PUT /test HTTP/1.1" 302 -
[2020-02-24 04:44:06,687] INFO in _internal: 127.0.0.1 - - [24/Feb/2020 04:44:06] "PUT /test HTTP/1.1" 302 -

我在StackOverflow中查找了类似问题,但是没有找到任何可行的解决方案。这个问题似乎很容易解决,但花了我很多时间。

2 个答案:

答案 0 :(得分:0)

尝试: url_for('test')。我的猜测是圆点确实有些时髦。

答案 1 :(得分:0)

我在https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html上找到了清楚的解释。

303查看其他

可以在不同的URI下找到对请求的响应,并且 应该使用该资源上的GET方法进行检索。这个方法 主要是为了允许POST激活的脚本的输出 将用户代理重定向到所选资源。新的URI不是 原始请求资源的替代参考。 303 响应一定不能被缓存,但是对第二个响应 (重定向)请求可能是可缓存的。

不同的URI应该由“位置”字段中的 响应。除非请求方法是HEAD,否则的实体 响应应包含简短的超文本注释,并带有指向 新的URI。

话虽如此,更改默认代码302可以解决问题:

redirect(url_for('app.test_route'), code=303)