Python 在烧瓶中重定向时发出 POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15473626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make a POST request while redirecting in flask
提问by ln2khanal
I am working with flask. I am in a situation where I need to redirect a post request to another url preserving the request method i.e. "POST" method. When I redirected a "GET" request to another url which accepts "GET" request method is fine. Here is sample code with which I am trying the above..
我正在使用烧瓶。我处于需要将发布请求重定向到另一个保留请求方法(即“POST”方法)的 url 的情况。当我将“GET”请求重定向到另一个接受“GET”请求方法的 url 时。这是我正在尝试上述操作的示例代码..
@app.route('/start',methods=['POST'])
def start():
flask.redirect(flask.url_for('operation'))
@app.route('/operation',methods=['POST'])
def operation():
return "My Response"
I want to make a "POST" request to "/start" url which internally also makes a "POST" request to "/operation" url.If I modify code as like this,
我想向“/start”url发出“POST”请求,它在内部也向“/operation”url发出“POST”请求。如果我像这样修改代码,
@app.route('/operation',methods=['GET'])
def operation():
return "My Response"
code works fine for "GET" request. But I want to be able to make POST request too.
代码适用于“GET”请求。但我也希望能够发出 POST 请求。
采纳答案by mdeous
The redirectfunction provided in Flasksends a 302 status code to the client by default, and as mentionned on Wikipedia:
中redirect提供的函数Flask默认向客户端发送 302 状态代码,如维基百科所述:
Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g. POST). [1] For this reason, HTTP/1.1 (RFC 2616) added the new status codes 303 and 307 to disambiguate between the two behaviours, with 303 mandating the change of request type to GET, and 307 preserving the request type as originally sent.
许多 Web 浏览器以违反此标准的方式实现此代码,将新请求的请求类型更改为 GET,而不管原始请求中采用的类型(例如 POST)。[1] 为此,HTTP/1.1 (RFC 2616) 添加了新的状态代码 303 和 307 以消除两种行为之间的歧义,其中 303 强制将请求类型更改为 GET,而 307 保留原始发送的请求类型。
So, sending a 307 status code instead of 302 should tell the browser to preserve the used HTTP method and thus have the behaviour you're expecting. Your call to redirectwould then look like this:
因此,发送 307 状态代码而不是 302 应该告诉浏览器保留使用的 HTTP 方法,从而具有您期望的行为。您的调用redirect将如下所示:
flask.redirect(flask.url_for('operation'), code=307)

