Generating URLs and Handling Redirects in Flask with url_for
Flask provides the url_for() function to dynamically generate URLs for view functions instead of hardcoding them. This approach offers two key advantages: it avoids the need to update URLs manually across the codebase if routes change, and it automatically handles URL escaping for special characters and Unicode data.
The url_for() function takes the name of a view function as its first argument. Any additional keyword arguments correspond to route variables or are appended as query parameters.
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index():
# Generates: /article/1?page=1&name=1
print(url_for('show_article', aid=1, page=1, name=1))
return 'Hello World'
@app.route('/article/<aid>')
def show_article(aid):
# Generates: /?next=%2F
print(url_for('index', next='/'))
return f'Article List {aid}'
if __name__ == '__main__':
app.run(debug=True)
When executed, accessing the root path / prints /article/1?page=1&name=1, while visiting /article/1 prints /?next=%2F, demonstrating how route parameters and query strings are handled.
Flask also supports HTTP redirects using the redirect() helper. This is commonly used to guide users to different pages—for example, redirecting unauthenticated users to a login page.
from flask import Flask, url_for, redirect, request
app = Flask(__name__)
@app.route('/login/', methods=['GET', 'POST'])
def login():
return 'Login Page'
@app.route('/profile/', methods=['GET', 'POST'])
def user_profile():
username = request.values.get('name')
if not username:
return redirect(url_for('login'))
return username
if __name__ == '__main__':
app.run(debug=True)
Accessing /profile/ without a name parameter triggers a redirect to /login/, illustrating conditional redirection based on request data.