article

Saturday, June 11, 2016

Python Flask Routing, Variable rules, URL Building

Python Flask - Routing, Variable rules, URL Building

Flask – Routing

The route() decorator in Flask is used to bind URL to a function. For example −


 
from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello_world():
   return 'hello world'

if __name__ == '__main__':
   app.run()
   
#http://127.0.0.1:5000/hello
Flask – Variable Rules It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as . It is passed as a keyword argument to the function with which the rule is associated.
 
from flask import Flask
app = Flask(__name__)

@app.route('/hello/')
def hello_name(name):
   return 'Hello %s!' % name

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/hello/tutorial101
The following output will be displayed in the browser.
Hello tutorial101!
In the following code, all these constructors are used.
 
from flask import Flask
app = Flask(__name__)

@app.route('/blog/')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/')
def revision(revNo):
   return 'Revision Number %f' % revNo

if __name__ == '__main__':
   app.run()
#http://127.0.0.1:5000/blog/11
#http://localhost:5000/rev/1.1
The given number is used as argument to the show_blog() function. The browser displays the following output −
Blog Number 11
Revision Number 1.100000
Flask – URL Building
The url_for() function is very useful for dynamically building a URL for a specific function.
The following script demonstrates use of url_for() function.
 
from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)
#http://127.0.0.1:5000/admin
#http://127.0.0.1:5000/guest/ednalan
#http://127.0.0.1:5000/guest/ednalan   
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest() function passing the received argument as guest parameter to it.
The application response in browser is −
Hello Admin
Hello mvl as Guest

Related Post