Flask Redirects
A redirect sends the browser to another address. The redirect call builds the 302 answer.
Make the app
This line imports Flask, redirect, and url_for together. The routes below belong to the app.
from flask import Flask, redirect, url_for
app = Flask(__name__)The home route
This route returns the home page. The old route below sends readers here.
@app.route("/")
def home():
return "Home page"The old address
This route redirects to home. url_for builds the address from the function name.
@app.route("/old")
def old():
return redirect(url_for("home"))Ask without and with following
The first ask shows the 302 status. The second ask follows the redirect and prints the home page.
client = app.test_client()
print(client.get("/old").status_code)
print(client.get("/old", follow_redirects=True).data.decode())Example
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route("/")
def home():
return "Home page"
@app.route("/old")
def old():
return redirect(url_for("home"))
client = app.test_client()
print(client.get("/old").status_code)
print(client.get("/old", follow_redirects=True).data.decode())Key points
- redirect sends a 302 status by default.
- url_for gives redirect the address to send.
- The browser follows the redirect on its own.
- The test client follows it only with follow_redirects=True.
In this example, the /old route redirects to home with url_for. The test client first asks for /old without following, and the print shows the 302 status. It then asks again with follow_redirects=True, and the print shows the home page.
Note
Redirects keep old addresses working after a move.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What status does a redirect send by default?