URL Building (url_for)
Hardcoding routes like "/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().
flowchart LR
A["url_for('user', name='ada')"] --> B["look up the endpoint 'user'"]
B --> C["find its rule /user/<name>"]
C --> D["fill the placeholders, percent-encoding as needed"]
D --> E["/user/ada"]
F["extra kwargs"] --> G["appended as a query string"]
H["_external=True"] --> I["absolute: http://host/user/ada"]
J["_anchor='top'"] --> K["adds #top"]
Basic usage
Section titled “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}"Key idea:
- You pass the endpoint name (usually the function name)
- And any variables required by the route
Why url_for is important
Section titled “Why url_for is important”- avoids broken links after refactors
- supports query parameters cleanly
- supports Blueprints (namespaced endpoints)
Query parameters with url_for
Section titled “Query parameters with url_for”url_for("search", q="flask", page=2)Output (conceptually):
/search?q=flask&page=2
Static files
Section titled “Static files”You’ll use:
url_for("static", filename="styles.css")That’s how templates should reference CSS/JS.
Debugging: what is my endpoint name?
Section titled “Debugging: what is my endpoint name?”Run:
flask routesIt lists endpoints and URL rules.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading