Глобальные зависимости и вложенные зависимости
Применяйте зависимости ко всему приложению или маршрутизатору, объединяйте вложенные зависимости и кэшируйте результаты зависимостей в рамках запроса, создавая чистые многоуровневые приложения FastAPI.
«Глобальные зависимости и вложенные зависимости» — бесплатный урок FastAPI Backend Development Bootcamp на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения FastAPI Backend Development Bootcamp, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс FastAPI Backend Development Bootcamp содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Scaling Up Dependencies
You can attach a dependency to a single route, but real apps need to apply checks broadly. FastAPI supports dependencies at the app, router, and route levels, plus dependencies that depend on other dependencies.
App-Level Dependencies
Pass dependencies=[...] to the FastAPI constructor to run them for every request. Useful for global logging or API-key checks.
from fastapi import FastAPI, Depends
async def verify_key():
...
app = FastAPI(dependencies=[Depends(verify_key)])Router-Level Dependencies
Attach dependencies to an APIRouter so they apply to every route in that router but not the whole app.
from fastapi import APIRouter, Depends
admin = APIRouter(
prefix='/admin',
dependencies=[Depends(verify_admin)],
)Dependencies Without a Return
When you only need a side effect (like raising on failure), put the dependency in the dependencies list rather than a parameter. Its return value is ignored.
@app.get('/secure', dependencies=[Depends(verify_key)])
async def secure():
return {'ok': True}Sub-Dependencies
A dependency can itself depend on another dependency. FastAPI resolves the whole chain automatically.
def get_token(authorization: str = Header(None)):
return authorization
def get_user(token: str = Depends(get_token)):
return lookup_user(token)
@app.get('/me')
async def me(user = Depends(get_user)):
return userWhy Layer Dependencies
Sub-dependencies let you compose small, single-purpose pieces: parse the token, then resolve the user, then check permissions. Each layer is reusable and independently testable.
Dependency Caching
Within a single request, FastAPI caches each dependency by default. If two dependencies both need get_user, it runs only once. Disable with Depends(fn, use_cache=False).
@app.get('/data')
async def data(
a = Depends(get_user),
b = Depends(get_user), # reuses cached result
):
return a is bModeling the Resolution Chain
The resolver walks dependencies depth-first and caches by function. Here is a simplified version in plain Python.
cache = {}
calls = []
def resolve(name):
if name in cache:
return cache[name]
calls.append(name)
cache[name] = name + '_value'
return cache[name]
resolve('get_user'); resolve('get_user'); resolve('get_token')
print(calls)Combining Levels
Precedence flows from broad to narrow: app dependencies run first, then router, then route. A request to a router route runs all three layers in order.
Overriding for Tests
Swap any dependency in tests with app.dependency_overrides to inject fakes without touching production code.
app.dependency_overrides[get_user] = lambda: {'id': 1, 'name': 'Test'}Best Practices
Keep dependencies focused:
- One responsibility per dependency.
- Use app/router level for cross-cutting concerns.
- Rely on caching; only disable it when you truly need fresh evaluation.
Quick Check
Two parameters in the same route both use Depends(get_user) with default settings. How many times does get_user run for one request?
Recap
You leveled up dependency injection:
- Applied dependencies at app, router, and route scope.
- Used side-effect-only dependencies in the
dependencieslist. - Chained sub-dependencies and relied on per-request caching.
- Overrode dependencies for testing.
Изучай FastAPI Backend Development Bootcamp с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 21
- Уроки
- 84
Часто задаваемые вопросы
Урок «Глобальные зависимости и вложенные зависимости» бесплатный?
Да — полный текст урока «Глобальные зависимости и вложенные зависимости» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс FastAPI Backend Development Bootcamp, подпишись на CoddyKit PRO. Курс FastAPI Backend Development Bootcamp содержит 4 уроков всего.
Чему я научусь в уроке «Глобальные зависимости и вложенные зависимости»?
Применяйте зависимости ко всему приложению или маршрутизатору, объединяйте вложенные зависимости и кэшируйте результаты зависимостей в рамках запроса, создавая чистые многоуровневые приложения FastAP… Ты практикуешь FastAPI Backend Development Bootcamp с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать FastAPI Backend Development Bootcamp?
Предыдущий опыт не требуется. FastAPI Backend Development Bootcamp на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Глобальные зависимости и вложенные зависимости»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке FastAPI Backend Development Bootcamp?
Да. Каждый урок FastAPI Backend Development Bootcamp включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Зависимости в FastAPI
- Внедрение общих зависимостей
- Зависимости на основе классов и yield
- Глобальные зависимости и вложенные зависимости