redirect() (Flask)

redirect() returns an HTTP redirect response that tells the browser to go to a different URL. In Flask it is almost always paired with url_for() so you redirect to a view by name rather than a literal path.

Flask

Redirects are essential after handling form submissions: process the POST, then redirect to a GET page so refreshing the browser does not resubmit the form (the Post/Redirect/Get pattern).

By default redirect() sends a 302 Found status. You can pass a code argument, such as redirect(url, code=301), for a permanent move. The function returns a Response object, so you return it from your view like any other response.

Combine it with flash() to leave a one-time message ('Saved!') that shows on the page you redirect to.

Syntax

from flask import redirect, url_for
return redirect(url_for("home"))

Examples

Python

from flask import redirect, url_for

@app.route("/old")
def old():
    return redirect(url_for("new"), code=301)

@app.route("/new")
def new():
    return "You arrived at the new page"

Learn it in a lesson

See also

Back to the Dictionary