0
0
FlaskHow-ToBeginner · 3 min read

How to Redirect in Flask: Simple Guide with Examples

In Flask, you redirect a user by returning redirect() with the target URL. Use url_for() to generate URLs dynamically for better code maintenance.
📐

Syntax

The basic syntax to redirect in Flask uses the redirect() function from flask. You pass the URL or endpoint to redirect to as an argument. For dynamic URLs, use url_for() to build the URL from the function name.

  • redirect(location): Sends the user to the given location.
  • url_for(endpoint, **values): Generates a URL for the given endpoint (function name) with optional parameters.
python
from flask import redirect, url_for

# Redirect to a fixed URL
return redirect('/home')

# Redirect using url_for to a function named 'home'
return redirect(url_for('home'))
💻

Example

This example shows a simple Flask app with two routes. The root route redirects to the /welcome route using redirect() and url_for(). The /welcome route displays a welcome message.

python
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    # Redirect to the welcome page
    return redirect(url_for('welcome'))

@app.route('/welcome')
def welcome():
    return 'Welcome to the Flask app!'

if __name__ == '__main__':
    app.run(debug=True)
Output
When you visit http://localhost:5000/, the browser redirects to http://localhost:5000/welcome and shows: Welcome to the Flask app!
⚠️

Common Pitfalls

Common mistakes when redirecting in Flask include:

  • Forgetting to import redirect or url_for.
  • Passing a function name string directly to redirect() instead of using url_for().
  • Redirecting to a URL that does not exist, causing a 404 error.
  • Not returning the redirect response, which means the redirect won't happen.

Always return the redirect call and use url_for() for dynamic URLs.

python
from flask import redirect

# Wrong: passing function name string directly
# return redirect('welcome')  # This redirects to literal '/welcome' URL string, which may be okay but not dynamic

# Right: use url_for to get URL from function name
from flask import url_for
return redirect(url_for('welcome'))
📊

Quick Reference

Here is a quick summary of redirect usage in Flask:

FunctionPurposeExample
redirect(location)Redirects user to the given URL or pathreturn redirect('/home')
url_for(endpoint, **values)Generates URL for a route function dynamicallyurl_for('home')
Combining bothRedirect to a route by function namereturn redirect(url_for('home'))

Key Takeaways

Use Flask's redirect() function to send users to a different URL.
Use url_for() to generate URLs dynamically from route function names.
Always return the redirect response from your route function.
Avoid hardcoding URLs; prefer url_for for maintainability.
Import redirect and url_for from flask before using them.