Globalne zależności i zależności podrzędne
Stosuj zależności w całej aplikacji lub routerze, łącz zależności podrzędne i buforuj wyniki zależności w obrębie żądania, aby budować przejrzyste, warstwowe aplikacje FastAPI.
Globalne zależności i zależności podrzędne to bezpłatna lekcja FastAPI Backend Development Bootcamp na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej FastAPI Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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.
Często zadawane pytania
Czy lekcja „Globalne zależności i zależności podrzędne” jest bezpłatna?
Tak — pełny tekst „Globalne zależności i zależności podrzędne” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu FastAPI Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs FastAPI Backend Development Bootcamp zawiera 4 lekcji w sumie.
Co nauczysz się w „Globalne zależności i zależności podrzędne”?
Stosuj zależności w całej aplikacji lub routerze, łącz zależności podrzędne i buforuj wyniki zależności w obrębie żądania, aby budować przejrzyste, warstwowe aplikacje FastAPI. Ćwiczysz FastAPI Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć FastAPI Backend Development Bootcamp?
Nie wymagamy żadnego doświadczenia. FastAPI Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Globalne zależności i zależności podrzędne”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji FastAPI Backend Development Bootcamp?
Tak. Każda lekcja FastAPI Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Zależności w FastAPI
- Wstrzykiwanie typowych zależności
- Zależności oparte na klasach i yield
- Globalne zależności i zależności podrzędne