Flask URL Building
In Flask, URL building is done using the url_for()
function, which dynamically generates URLs for your application’s routes. This is useful because it ensures that URLs are constructed correctly, even if routes change. The url_for()
function takes the name of a view function and any arguments required to build the URL.
app.py
from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin') def admin(): return 'Hello Admin' @app.route('/guest/<guest>') def guest(guest): return f'Welcome {guest}' @app.route('/user/<name>') def user(name): if name =='admin': return redirect(url_for('admin')) else: return redirect(url_for('guest',guest = name)) if __name__ == '__main__': app.run(debug=True)
Output:
- When a user visits
http://127.0.0.1:5000/user/admin
- Redirects to
/admin
- Output: "Hello Admin".
- When a user visits
http://127.0.0.1:5000/user/vrsofttech
- Redirects to
/guest/vrsofttech
- Output: "Welcome vrsofttech".