URL Building (url_for)
Hardcoding routes like "/user/123""/user/123" is fragile.
If you rename the route later, you must update every place that used the string.
Flask’s best practice is to generate URLs with url_for()url_for().
Basic usage
from flask import Flask, url_for
app = Flask(__name__)
@app.route("/")
def home():
profile_url = url_for("profile", username="ravi")
return f"Profile link: {profile_url}"
@app.route("/user/<username>")
def profile(username):
return f"Profile: {username}"from flask import Flask, url_for
app = Flask(__name__)
@app.route("/")
def home():
profile_url = url_for("profile", username="ravi")
return f"Profile link: {profile_url}"
@app.route("/user/<username>")
def profile(username):
return f"Profile: {username}"Key idea:
- You pass the endpoint name (usually the function name)
- And any variables required by the route
Why url_for is important
- avoids broken links after refactors
- supports query parameters cleanly
- supports Blueprints (namespaced endpoints)
Query parameters with url_for
url_for("search", q="flask", page=2)url_for("search", q="flask", page=2)Output (conceptually):
/search?q=flask&page=2/search?q=flask&page=2
Static files
You’ll use:
url_for("static", filename="styles.css")url_for("static", filename="styles.css")That’s how templates should reference CSS/JS.
Debugging: what is my endpoint name?
Run:
flask routesflask routesIt lists endpoints and URL rules.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
