English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask URL Construction

The url_for() function is very useful for dynamically constructing the URL of a specific function. The function accepts the name of the function as the first parameter, and accepts one or more keyword arguments, each corresponding to a variable part of the URL.

The following script demonstrates the use of the url_for() function.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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 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 script has a function user(name), which accepts parameter values from the URL.

The User() function checks if the received parameters match 'admin'. If they match, it uses url_for() to redirect the application to the hello_admin() function, otherwise it passes the received parameters as the guest parameter to the hello_guest() function.

Save the above code to a file: hello.py, and run from the Python shell.

Open the browser and enter the URL - http://localhost:5000/user/admin

The application response output result in the browser is -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
Hello Admin

Enter the following URL in the browser - http://localhost:5000/user/mvl

The application response result is now changed to -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
Hello mvl as Guest