Извлечение переменных из пути
Используйте параметры в угловых скобках в маршрутах.
«Извлечение переменных из пути» — бесплатный урок Flask Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Flask Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Flask Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Static Routes Hit a Wall
A fixed path like /user/alice only works for one person. To serve any name, you need a route that captures part of the URL as data.
Angle Brackets Capture Values
Wrap a path segment in angle brackets to turn it into a variable. Flask grabs whatever the user types there and hands it to your view as a parameter. 🎯
@app.route('/user/<name>')
def profile(name):
return f'Hello, {name}!'The Name Must Match
The word inside the brackets becomes the function argument. The name in the URL and the parameter in your view function must be spelled identically.
@app.route('/city/<place>')
def show(place):
return placeValues Arrive as Strings
By default a captured value is always a Python string. Visiting /user/42 gives you the text "42", not the number 42.
@app.route('/id/<value>')
def show(value):
return type(value).__name__Capture More Than One
A single route can capture several segments. Each set of angle brackets becomes its own argument in the view function, in order.
@app.route('/<category>/<item>')
def show(category, item):
return f'{category}: {item}'Mix Fixed and Dynamic Parts
You can blend static text with captured pieces. Only the bracketed segment is dynamic; the rest of the path stays fixed and literal.
@app.route('/posts/<slug>/edit')
def edit(slug):
return slugUse the Value in Your Logic
Once captured, the variable is just normal Python. Look it up in a database, format it, or branch on it like any other value.
@app.route('/user/<name>')
def hi(name):
return f'Welcome back, {name.title()}'Each Request Is Independent
Every visit fills the captured variable fresh. One user hitting /user/sam and another hitting /user/lee get separate, isolated requests.
Slashes Split Segments
A normal capture stops at the next slash. So name in /user/<name> will not include any /, since the slash marks the end of that segment.
Naming Your Variables Well
Pick clear names that describe the data, like <username> or <product_id>. Good names make routes self-documenting and easier to maintain.
A Tiny Real Example
Captured variables power friendly URLs like /greet/Maria. The view simply uses the value to build a personalized response for each visitor.
@app.route('/greet/<who>')
def greet(who):
return f'Nice to meet you, {who}'Quick Check
You wrote /user/<name> with def profile(name). What gets passed to name?
Recap: You Captured the Path
Angle brackets turn part of a URL into a function argument. Captured values arrive as strings, and you can grab several at once. Next: typing them. 🚀
Часто задаваемые вопросы
Урок «Извлечение переменных из пути» бесплатный?
Да — полный текст урока «Извлечение переменных из пути» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Flask Academy, подпишись на CoddyKit PRO. Курс Flask Academy содержит 4 уроков всего.
Чему я научусь в уроке «Извлечение переменных из пути»?
Используйте параметры в угловых скобках в маршрутах. Ты практикуешь Flask Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Flask Academy?
Предыдущий опыт не требуется. Flask Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Извлечение переменных из пути»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Flask Academy?
Да. Каждый урок Flask Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Извлечение переменных из пути
- Преобразователи типов: int, float, string, path
- Построение URL с помощью url_for
- Завершающие косые черты и перенаправления