Speed up development with full-stack environments for every branch.

Learn More

Redirects in Flask [Python]

1107 Runs 17626 Views 2561 Copies


mmolina 24

published 4 years ago

# We need to import the redirect module in order to be able to perform 
# redirects. url_for will come handy to extract the url for routes
from flask import Flask, redirect, url_for

# Initialize the Flask application
app = Flask(__name__)

# Define a default root route, which will just print a Hello World! message
# and a link to other routes, to make it easier to test them
def index():
  return 'Hello World! Go to <a href="/admin">admin<a>'
# Now when users browse the landpage of the admin section, we want to redirect
# them to the login page. 
def admin():
  # The default redirect is a HTTP 302 Moved Temporarily. More info:
  # http://en.wikipedia.org/wiki/HTTP_302
  # Later on we'll show how to perform different types of redirects.
  return redirect(url_for('login'))
# Imagine we used to have an old page on our site, but we want to
# permanently redirect all its request to a new url, runnable.com for example
def old_page():
  # The second parameter of the redirect function is where we
  # specify what type of redirect we want to perform, 301 in this case.
  # HTTP 301 Moved Permanently - http://en.wikipedia.org/wiki/HTTP_301
  return redirect('http://www.runnable.com', 301)

# Route to show the login form.
# Note: As using forms, loading templates, etc. is covered by other runnable
# examples we will just show a login message, and a link to go back
def login():
  return 'You should login! Go to back to <a href="/">the beginning<a>'

if __name__ == '__main__':
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).