Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a POST request while redirecting in flask

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..

@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,

@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.

like image 627
ln2khanal Avatar asked Mar 18 '13 09:03

ln2khanal


People also ask

Can POST requests be redirected?

in response to a POST request. Rather, the RFC simply states that the browser should alert the user and present an option to proceed or to cancel without reposting data to the new location. Unless you write complex server code, you can't force POST redirection and preserve posted data.


1 Answers

The redirect function provided in Flask sends a 302 status code to the client by default, and as mentionned on Wikipedia:

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.

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 redirect would then look like this:

flask.redirect(flask.url_for('operation'), code=307) 
like image 58
mdeous Avatar answered Sep 20 '22 04:09

mdeous