Построение URL с помощью url_for
Создавайте ссылки по именам конечных точек, а не по жёстко заданным путям.
«Построение URL с помощью url_for» — бесплатный урок Flask Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Flask Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Flask Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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. 🧩
Часто задаваемые вопросы
Урок «Построение URL с помощью url_for» бесплатный?
Да — полный текст урока «Построение URL с помощью url_for» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Flask Academy, подпишись на CoddyKit PRO. Курс Flask Academy содержит 4 уроков всего.
Чему я научусь в уроке «Построение URL с помощью url_for»?
Создавайте ссылки по именам конечных точек, а не по жёстко заданным путям. Ты практикуешь Flask Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Flask Academy?
Предыдущий опыт не требуется. Flask Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Построение URL с помощью url_for»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Flask Academy?
Да. Каждый урок Flask Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Извлечение переменных из пути
- Преобразователи типов: int, float, string, path
- Построение URL с помощью url_for
- Завершающие косые черты и перенаправления