Flask - Binding URL
First thing that comes to mind when we here binding is - I guess - BOOK BINDING / PAPER BINDING. Well this is something similar to that but not exactly. Here, in Flask, binding URL means adding functionalities to some URL.
url_for() is a very useful function used to dynamically build
URL for a specific function. It accepts the first parameter to be the function that needs to be bind, followed with one or more keyword arguments, each corresponding to the variable part of URL
Example
from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>') 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)
In the above example see that the redirect() function is being used to navigate the page to url_for() function page.
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is moved to the hello_admin() function using url_for(), otherwise it is moved to the hello_guest() function passing the received argument as guest parameter to it.
When you run the code, launch browser and open URL − http://localhost:5000/user/admin you will get an output -
Hello Admin
Now use this URL to see the change - http://localhost:5000/user/Vikash
you will get output as -
Hello Vikash as Guest
So now, when we know the few basic things of Flask, it'll become even easy and better to move forward..
Thanks again for the article post.Really thank you! Fantastic.
ReplyDeletejava online training
java training