Stage 4 · L19
Resolve dependencies and distinguish cleanup from commit
Core · original Session 4
Depends declares how a route obtains a resource or collaborator. FastAPI resolves the dependency when handling the request; you should not call the dependency manually with an unresolved Depends object. session_dependency creates one session, yields it to the handler, and closes it afterwards. In the pinned FastAPI runtime, function scope completes cleanup before sending the response.
Dependency cleanup and transaction success are different decisions. Closing a session rolls back unfinished work; it does not commit merely because a route returned a dictionary. The service's with session.begin establishes successful commit and exception rollback. A read may auto-begin a transaction which cleanup will finish by closing, without creating a write.
Request-scoped dependency caching can reuse a resolved dependency within one request. It is not a global session singleton or a cross-request cache. Sharing one mutable Session across requests can mix object identity and transaction state. The engine/factory may live at app scope; sessions need narrower ownership.
Tests may override session_dependency with a factory for the owned fixture. Always restore app.dependency_overrides in finally so one test cannot change the next test's storage or actor. The checkpoint uses this override to count SQL for a nested page later. A mock or override establishes only the boundary it substitutes; it does not certify PostgreSQL rollback unless real rows are involved.
Dependencies may depend on other dependencies. The actual stage04 session_factory dependency returns the app's factory; session_dependency receives it via Depends, opens one session and yields it. Later require→current_actor→HTTPBearer forms another chain. FastAPI resolves the declared graph; ordinary direct function calls do not magically turn a Depends marker into a resource. Override the intended node in a test and restore it.
Follow the running code
Focused lesson example; see the end-of-stage capstone for the cumulative app · stage 04
def session_factory():
return SessionLocal
def session_dependency(factory=Depends(session_factory)):
with factory() as session:
yield session
# Dependency cleanup owns close; the business transaction owns commit.Predict and observe this focused example using the concepts explained above. Its boundary is stated in the focused answer.
Guided lab
- Read the explanation and predict the focused example’s outcome.
- Draw the factory→session→handler dependency graph and predict cleanup after an exception. Explain how an override changes the test boundary.
- Compare the observed outcome with the focused answer and state its boundary.
Expected: FastAPI resolves the factory before creating the per-request session. The context closes/rolls back unfinished work on exit; returning from a handler is not a commit instruction. Request caching is not a cross-request singleton. An override chooses a collaborator for the test and must be restored; it does not prove behavior behind the replaced boundary.
- A leaked override contaminates later tests; a closed session does not prove a successful write committed.
Focused exercise and answer
Complete this focused exercise before reading its answer. The full native transfer is introduced only at the end of the stage.
Your transfer task: Draw the factory→session→handler dependency graph and predict cleanup after an exception. Explain how an override changes the test boundary.
- Draw the factory→session→handler dependency graph and predict cleanup after an exception. Explain how an override changes the test boundary.
Inspect the matching answer
This answer addresses the focused exercise above; the cumulative implementation is shown only after the stage prerequisites.
FastAPI resolves the factory before creating the per-request session. The context closes/rolls back unfinished work on exit; returning from a handler is not a commit instruction. Request caching is not a cross-request singleton. An override chooses a collaborator for the test and must be restored; it does not prove behavior behind the replaced boundary.Check your reasoning
Should dependency teardown decide every business commit?
Show the explanation
No. Resource cleanup belongs to the dependency; successful operation completion belongs to the service's transaction boundary.
Reading progress
54 lessons remain open to guests. Marking a lesson read records reading only; it does not award assessment credit or a certificate.
Device reading marks require browser storage. Reading is always available.
Sign in or create an account to save separate account progress. Your current page is kept.
Your earlier place on this device suggests these lessons. No new lesson is marked read.