url_for () function is to build a dynamic URL to a specific function is very useful. This function takes a name as a function of the first parameter takes one or more keywords and parameters, each parameter corresponding to the variable portion of the URL.
The following script demonstrates the 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/<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)
The above script has a function user (name) , which takes the parameter values from the URL.
The user () function checks the received parameters match "administrator" or not. If so, use the url_for () will be redirected to the application
hello_admin () function, otherwise the received parameters passed as a parameter to the guest hello_guest () function. **** ****
Save the above code and run from the Python shell.
Open a browser and enter the URL of - HTTP: // localhost: 5000 / the User / ADMIN
Application Browser in the response is -
Hello Admin
Enter the following URL in your browser - HTTP: // localhost: 5000 / the User / MVL
Application response now becomes -
Hello mvl as Guest
This switched: http: //codingdict.com/article/4868