Construya URL con url_for
Genere enlaces a partir de nombres de endpoints, no de rutas codificadas.
Construya URL con url_for es una lección gratuita de Flask Academy en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Flask Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Flask Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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. 🧩
Preguntas frecuentes
¿La lección «Construya URL con url_for» es gratis?
Sí — el texto completo de «Construya URL con url_for» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Flask Academy, actualiza a CoddyKit PRO. El curso de Flask Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Construya URL con url_for»?
Genere enlaces a partir de nombres de endpoints, no de rutas codificadas. Practicas Flask Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Flask Academy?
No se requiere experiencia previa. Flask Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Construya URL con url_for»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Flask Academy?
Sí. Cada lección de Flask Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Capture variables de la ruta
- Convertidores de tipos: int, float, string, path
- Construya URL con url_for
- Barras finales y comportamiento de redirección