Redirect After Post in Flask
Redirect after post stops double sends. The view saves the value, then redirects to a fresh page.
Make the app
This line imports Flask, request, redirect, and url_for together. The list below holds saved words.
from flask import Flask, request, redirect, url_for
app = Flask(__name__)
saved = []Save, then redirect
The POST route saves the word in the list. It then redirects to the show page instead of answering directly.
@app.route("/save", methods=["POST"])
def save():
saved.append(request.form.get("word", ""))
return redirect(url_for("show"))Show the saved words
This plain GET route joins the saved words into one line.
@app.route("/show")
def show():
return "Saved: " + ", ".join(saved)Post, then check the redirect
The first ask posts hello and prints the 302 status. The second ask follows the redirect and prints the saved words.
client = app.test_client()
print(client.post("/save", data={"word": "hello"}).status_code)
print(client.post("/save", data={"word": "hello"}, follow_redirects=True).data.decode())Example
from flask import Flask, request, redirect, url_for
app = Flask(__name__)
saved = []
@app.route("/save", methods=["POST"])
def save():
saved.append(request.form.get("word", ""))
return redirect(url_for("show"))
@app.route("/show")
def show():
return "Saved: " + ", ".join(saved)
client = app.test_client()
print(client.post("/save", data={"word": "hello"}).status_code)
print(client.post("/save", data={"word": "hello"}, follow_redirects=True).data.decode())Key points
- A refresh after a POST sends the form again.
- Redirecting to a GET page ends the POST.
- The pattern is called Post Redirect Get.
- The saved value shows on the GET page.
In this example, the /save route appends the posted word to the list and redirects to /show. The test client posts hello twice. The first print shows the 302 status of the plain post. The second post follows the redirect, and the print shows both saved words on the show page.
Note
The redirect target is a plain GET route.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does a view redirect after saving a form post?