HTTP Redirect
In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3
, and a Location
header holding the URL to redirect to.
When browsers receive a redirect, they immediately load the new URL provided in the Location
header. Besides the small performance hit of an additional round-trip, users rarely notice the redirection.
Simple Flask sample app
We will create a simple Flask application to demonstrate this. Here are the files we are going to need:
app.py
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
@app.route("/form", methods=["POST", "GET"])
def name_form():
if request.method == "POST":
return redirect(url_for("hello", name=request.form.get("name", None)))
return render_template("form.html")
@app.route("/hello/<name>")
def hello_name(name=None):
return render_template("hello.html", name=name)
Note that we have used the redirect()
method in name_form()
view. When the user enters a name, they are redirected to another page showing a greeting with the name they entered.
We also need two simple templates we use which you need to place in the templates/ folder. We will not be trying to beautify the pages since that is not the focus of this article.
templates/form.html:
<!DOCTYPE html>
<form method="POST">
<label>Enter your name:</label>
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
templates/hello.html:
<!DOCTYPE html>
<p>
{% if name %}
<h1>Hello {{name}}</h1>
{% else %}
<h1>Hello user<</h1>
{% endif %}
</p>
This is what our folder structure looks like:
Demo
Let's run the app using flask run --debug
and navigate to /form
. Remember to press F12 to open developer tools.
Enter any name and click on submit. I entered 'Rohan', and now this is what you will see in the browser:
Now go to the network tab in developer tools:
Notice, that the response to the form submission didn't directly send you the new page. Instead, the server sent a 302
code along with a Location
header.
HTTP/1.1 302 Found
Location: /hello/Rohan
The browser then requested the new URI specified by the Location
header.
Summary
We have explored what is HTTP redirection and how it works in a browser. Then, for demonstration, we wrote a simple application using Python Flask.
Thanks for reading and I hope you found this article useful.