Make a POST request while redirecting in flask

PythonRedirectFlask

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionln2khanalView Question on Stackoverflow
Solution 1 - PythonmdeousView Answer on Stackoverflow