Real-world mechanisms, state management, edge cases, performance trade-offs, and practical coding.
async def app(scope, receive, send) handling HTTP/WebSocket/lifespan messages.@app.on_event("startup") legacy / lifespan context manager modern) initialize pools (DB, Redis, httpx clients) once per process — dependencies then reuse them.Depends(get_db) in handler + sub-dependency shares the session.use_cache=False on Depends when you genuinely need fresh resolution (per-item security checks in loops).async def get_db():
async with async_session() as s:
yield s
class RoleChecker:
def __init__(self, *roles): self.roles = set(roles)
def __call__(self, user: User = Depends(get_current_user)):
if user.role not in self.roles: raise HTTPException(403)
@router.post("/admin", dependencies=[Depends(RoleChecker("admin"))])
Security(get_current_user, scopes=["items:write"]); token contains scopes; SecurityScopes dependency verifies hierarchy — maps to OpenAPI security UI.@field_validator("email")
@classmethod
def normalize(cls, v): return v.lower()
@model_validator(mode="after")
def check_dates(self):
if self.end < self.start: raise ValueError(...)
You've completed the 5 free sample questions. Get unrestricted lifetime access to every question, model answer, implementation challenge, and all 27+ technologies for a single payment.
₹399 India / $9 International · One-time settlement · Zero subscription