Speed up development with full-stack environments for every branch.Learn More
Redirects in Flask [Python]
1075 Runs 16663 Views 2409 Copies
# 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 @app.route('/') 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. @app.route('/admin') 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 @app.route('/old_page') 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 @app.route('/admin/login') def login(): return 'You should login! Go to back to <a href="/">the beginning<a>' if __name__ == '__main__': app.run( host="0.0.0.0", port=int("80") )
Please login/signup to get access to the terminal.