Explain Codes LogoExplain Codes Logo

Redirecting to URL in Flask

python
redirect
url-for
flask
Anton ShumikhinbyAnton Shumikhin·Mar 4, 2025
TLDR

To perform URL redirection in Flask, combine redirect() and url_for() functions like this:

from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/go-to-target') def go_to_target(): # Whoosh! Off we go to the target! return redirect(url_for('target')) @app.route('/target') def target(): return "Conductor: We've reached the destination, folks!" # Time to get this train moving! app.run()

Navigating to /go-to-target will whisk you away to the /target page.

Fundamentals of redirection in Flask

Redirection is Flask's way of saying, "Hey, let's go somewhere else." You, as the controller of this operation, get to use the redirect() function to determine the destination. The HTTP status codes (301, 302, 303, 305, or 307) serve as your trusty navigational compass, directing the user's browser accordingly. In most cases, 302 is the default guide, but feel free to choose your own adventure!

Dynamic URL construction with url_for()

Routing in Flask is like trying to navigate an intricate web of subway lines. Here's where url_for() steps in to play the role of your route planner. This function lets you generate dynamic URLs, so you can sat goodbye to hardcoding those complicated URL rules and make your web journey clean and maintainable.

Pre-flight checklist for redirection

Before taking off with redirection, make sure your Flask is fired up and ready:

from flask import Flask, redirect, url_for app = Flask(__name__) # Ready to map out the journey ahead!

Having set the stage, it's time to define the routes and view functions. Buckle up and let flask.redirect() take the wheel!

Tips and tricks for a smooth redirect journey

Picking the right travel guide: status code

Feel like changing the nature of your redirect journey? Easy, just switch your tour guide! For example, for a permanent change of scenery, choose 301:

return redirect(url_for('new_place'), 301) # Permanent, pack all your stuff!

Handling detours gracefully

Sometimes, the journey isn’t straightforward; we might have to take a detour due to an errant form submission, or maybe an error, perhaps a dragon? Jokes aside, the combination of redirect() and flash() comes in handy to steer users in the right direction:

from flask import Flask, redirect, url_for, flash @app.route('/submit-form', methods=['POST']) def submit_form(): # Here be dragons! just kidding, form processing if form_is_valid(): # Wohoo! We're on the right track! return redirect(url_for('success')) else: flash('Darn dragon! Form submission thwarted. Please retry.') return redirect(url_for('form')) @app.route('/success') def success(): # Bottle of champagne, anyone? return "Form submitted! We've got ourselves a winner!" @app.route('/form') def form(): # Back to square one, folks! return render_template('form.html')

Keeping your baggage intact with query parameters

Say you are travelling from New York to London, but you don't want to lose any query parameters in transit. Here's a neat trick to keep your bags packed during the redirect:

from flask import request @app.route('/redirect') def redirect_with_params(): params = request.args # Hold onto your luggage, folks! return redirect(url_for('new_route', **params))

Landing on the right runway with hosting and port binding

Just like you wouldn't want your plane landing on someone else's runway, you need to be careful about your hosting environment when setting up your URLs. Remember, url_for() has a helpful _external=True parameter for creating full absolute URLs.

Useful redirect patterns and potential potholes

Trailing slashes: To be or not to be

In Flask, "trailing slashes" are a story of star-crossed routes. When Romeo (your redirect function) tries to reach Juliet (the route) with incorrect trailing slashes, it's a recipe for a tragedy (HTTP 404 error):

# Juliet: This route insists on a trailing slash @app.route('/about/') def about(): # ...

But fear not, for here’s your happy ending:

return redirect(url_for('about')) # Flask Romeo auto-corrects to '/about/', star-crossed no more!

Avoiding the siren’s call: Open redirect vulnerabilities

When you are redirecting based on user feedback, walk cautiously. Try to avoid the siren's call, aka open redirect vulnerabilities, by ensuring input validation:

from flask import request @app.route('/search') def search(): query = request.args.get('q') if is_valid_query(query): # Query approved! Let's embark on the grand adventure. return redirect(url_for('results', query=query)) else: # Attention, folks: Please double-check your query. return "Invalid search query."

Keeping up with Flask's pace

Remember, as savvy travellers, we adapt to new versions. flask.redirect() is compatible with Flask versions 0.6 and higher, ensuring your app sails smoothly across different environments.