Creare URL con url_for
Generi link dai nomi degli endpoint, non da percorsi codificati.
Creare URL con url_for è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Hardcoded URLs Are Fragile
Typing "/user/alice" by hand breaks the day you rename a route. Flask offers url_for to build links from your view names instead.
Build by Endpoint Name
url_for takes the view function name and returns its path. Change the route string later and every generated link updates automatically. 🔗
from flask import url_for
url_for('home')The Endpoint Is the Function Name
By default the endpoint is the view function's name, not its URL path. So def home() is referenced as url_for('home').
@app.route('/')
def home():
return 'Hi'Pass Dynamic Values
For routes with captured parts, supply them as keyword arguments. url_for drops each value into the matching angle-bracket slot.
url_for('profile', name='alice')
# -> '/user/alice'Extra Args Become Query Strings
Arguments that do not fit a route slot are added as a query string. So passing page=2 appends ?page=2 to the generated URL.
url_for('search', q='cats', page=2)
# -> '/search?q=cats&page=2'Use It Inside Templates
Templates call url_for too, so your HTML links never go stale. It is the standard way to write hrefs in Jinja2 pages.
<a href="{{ url_for('home') }}">Home</a>Refactor Without Fear
Because links derive from endpoint names, you can rename a URL path freely. Every url_for call keeps working, so refactors stay safe.
Redirect Pairs Well with It
Combine url_for with redirect to send users to a named view. You get a clean, refactor-proof redirect without writing the path by hand.
from flask import redirect
redirect(url_for('home'))Absolute URLs When Needed
Pass _external=True to get a full http://host/path link. This is handy for emails or anywhere a relative path will not do.
url_for('home', _external=True)It Knows the static Folder
url_for also builds links to assets via the static endpoint. That keeps CSS and image paths correct even if your app mounts elsewhere.
url_for('static', filename='app.css')A Habit Worth Forming
Make url_for your default for every internal link. Hardcoded strings creep in and rot; generated URLs stay correct as your app evolves.
Quick Check
You call url_for('profile', name='alice', page=2). Where does page=2 end up?
Recap: You Built URLs Smartly
url_for turns endpoint names into paths, fills route variables, and tacks extras onto the query string. Next: trailing slashes. 🧩
Domande Frequenti
La lezione «Creare URL con url_for» è gratuita?
Sì — il testo completo di «Creare URL con url_for» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.
Cosa imparerò in «Creare URL con url_for»?
Generi link dai nomi degli endpoint, non da percorsi codificati. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Flask Academy?
Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.
Quanto tempo richiede la lezione «Creare URL con url_for»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Flask Academy?
Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Catturare variabili dal percorso
- Convertitori di tipo: int, float, string, path
- Creare URL con url_for
- Slash finali e comportamento dei redirect