تزریق وابستگی با Depends: زیروابستگیها، Cache، وابستگیهای سراسری و Router و Override
"'Dependency Injection' means, in programming, that there is a way for your code (in this case, your path operation functions) to declare things that it requires to work and use: 'dependencies'." — مستندات FastAPI، «Dependencies»، fastapi.tiangolo.com/tutorial/dependencies
خلاصه (Summary): تزریق وابستگی (Dependency injection) در FastAPI حلکنندهای داخل مسیریاب (Router) با حوزهٔ درخواست (Request scope) است. عملیات مسیر (Path operation) نیازهایش را با پارامترهایی مثل session: SessionDep و user: CurrentUser اعلام میکند. هر وابستگی (Dependency) از فراهمکننده (Dependable) میآید؛ یعنی شیء قابل فراخوانی (Callable) معمولی که به Depends() میدهیم. FastAPI هنگام import امضاها را میخواند و گراف وابستگی (Dependency graph) میسازد. در هر درخواست آن را عمقاول حل میکند، ورودی پرسوجو (Query)، سرآیند (Header)، کوکی (Cookie) و بدنه (Body) هر Dependable را میخواند، تابع را فراخوانی میکند و نتیجه را تا پایان درخواست در حافظهٔ نهان (Cache) نگه میدارد و تزریق میکند. تابع همگام (sync) در مجموعهٔ threadها (Thread pool) اجرا میشود. Dependency مولد با yield مرحلهٔ آمادهسازی (Setup) و جمعکردن منابع (Teardown) دارد. برای اثر جانبی (Side effect) مثل احراز هویت (Authentication) میتوان آن را به تزئینگر (Decorator)، Router یا کل برنامه وصل کرد؛ app.dependency_overrides هم هر گره را در تست عوض میکند. تمرکز (Focus): معنای DI و وارونگی کنترل (Inversion of control)، Depends() با تابع و کلاس، نام مستعار (Alias) مبتنی بر Annotated مثل SessionDep، زیروابستگی (Sub-dependency) و ترتیب حل گراف؛ Cache درخواست، use_cache=False و کلید شامل Callable، حوزههای امنیتی (Security scopes) و scope؛ کار yield، Setup و Teardown و finally، استثنا و ترتیب پاکسازی نسبت به پاسخ و کار پسزمینه (Background task) و Depends(scope="function")؛ Dependency Decorator، APIRouter و FastAPI(dependencies=...)؛ تنظیم Dependency با کلاس Callable و کارخانهٔ Closure، انتخاب async یا sync، تزریق Request و Response، request.state و وضعیت چرخهٔ عمر (Lifespan state)؛ آشنایی با OAuth2PasswordBearer، Security() و SecurityScopes، استفاده از app.dependency_overrides، تفاوت موتور (Engine) و نشست (Session) و عمر تکنمونه (Singleton) با عمر درخواست، max_concurrency، خطر وضعیت سراسری تغییرپذیر، مکانیاب سرویس (Service locator) و تزریق بیشازحد (Over-injection)، و مقایسه با Service container در Laravel و تزریق سازنده (Constructor injection) در Go با wire و fx. هدف یادگیری (Learning goal): Dependencyهای سرویس را طوری طراحی کنید که هر Route دقیقاً نیازش را اعلام کند، هر منبع عمر درستِ پردازه (Process)، درخواست یا تابع را داشته باشد، پاکسازی همیشه انجام شود، Authentication و جداسازی مستأجر (Tenant) در یک جا اعمال شوند و هر جزء خارجی با یک مدخل دیکشنری در تست جایگزین شود.
این صفحه Depends و همهٔ کارهای سیستم Dependency را پوشش میدهد. موضوع همسایهها را دوباره درس نمیدهیم: Routeها، پارامترها و مبانی چرخهٔ عمر (Lifespan) در مبانی FastAPI هستند. Query()، Header()، Cookie و اعتبارسنجها در اعتبارسنجی درخواست آمدهاند؛ Dependency درست مثل Route از آنها استفاده میکند. APIRouter، Prefix و چیدمان پروژه در ساختار پروژه و APIRouter، Engine و Session و مدلها در SQLAlchemy 2 و SQLModel، هش گذرواژه و JWT و بررسی واقعی Token در احراز هویت FastAPI، وضعیت آمادهٔ تست (Fixture) و دستور کامل پایگاه دادهٔ تست در تست FastAPI، و کارگر (Worker) و اندازهٔ استخر (Pool) در FastAPI در Production هستند. اصل پشت همهٔ اینها اصل وارونگی وابستگی است. همتای Go در Mock با Interface و DI برای تستپذیری و جهت Dependencyها میان لایهها در معماری Clean، Hexagonal و Onion آمده است.
حقایق این صفحه با آموزش و راهنمای پیشرفتهٔ FastAPI دربارهٔ Dependency، کلاس، Sub-dependency، Decorator، Dependency سراسری، yield، تست، امنیت، Lifespan و استفادهٔ مستقیم از درخواست بررسی شدهاند. مرجع Depends() و Security()، یادداشتهای انتشار تا 0.165.0 در ۲۰۲۶-۱۱-۱۸، کد ذخیرهشدهٔ FastAPI 0.128.8 در fastapi/dependencies/utils.py، models.py و params.py، مستندات Starlette دربارهٔ درخواست، برنامه، Lifespan و Thread pool، PEP 593، راهنمای Session در SQLAlchemy 2.0، آموزش SQLModel، Service container در Laravel 13، مستندات google/wire و uber-go/fx و مقالهٔ سال ۲۰۰۴ Martin Fowler نیز مبنا بودهاند. صفحه برای Python 3.12+ و FastAPI جاری نوشته شده است. قطعهکدها (Snippets) با تنها مفسر ماشین Build، CPython 3.9.6، و جدیدترین نسخههای قابل نصب روی آن اجرا شدند: FastAPI 0.128.8 (از 0.129.0 پشتیبانی 3.9 حذف شد)، Starlette 0.49.3، Pydantic 2.13.5، SQLAlchemy 2.0.58، Uvicorn 0.39.0، httpx 0.28.1، pytest 8.4.2 و eval-type-backport. هر ترتیب رویداد، کد وضعیت، Header و خطایی که «واقعی» نامیده شده، خروجی همان اجراست. ویژگیهای بعد از 0.128.8 از یادداشتهای انتشار توضیح داده شدهاند و مشخصاند: max_concurrency در 0.163.0، اصلاح پاکسازی هنگام لغو در 0.162.x، Dependency امنیتی WebSocket در 0.144.0، درخت Router در 0.137.0 و دسترسی دیکشنری request.state[...] در Starlette 0.52.0.
نقشهٔ صفحه (Page map)
| اگر دنبال این هستید | بروید به |
|---|---|
| جدولهایی که باید حفظ باشید | همهچیز در یک دقیقه |
| چرا چارچوب (Framework) نیازهای کد را تزریق میکند | چرا وجود دارد |
| تاریخچه از Fowler در 2004 تا FastAPI 0.165 | از کجا آمده |
| سرویس قبل و بعد از اصلاح | Python |
| معنای DI، IoC، Dependable و Dependant | DI چیست |
اعلام نیاز با Depends(fn) | Depends و Dependable |
استفاده از Depends() با کلاس | Dependency کلاسی |
تعریف SessionDep = Annotated[...] | Alias و SessionDep |
| نیازهای خود Dependency | Sub-dependency و گراف |
| کدام بخش زودتر اجرا میشود | ترتیب حل |
| معنای «یک بار در هر درخواست» | Cache و use_cache |
پاکسازی با yield و finally | Dependency مولد |
HTTPException و except در Dependency | استثناها |
| Teardown پس از پاسخ و Background task | زمان Teardown |
استفاده از @app.get(..., dependencies=[...]) | Dependency Decorator |
تنظیم APIRouter(dependencies=...) و FastAPI(dependencies=...) | Router و Dependency سراسری |
تنظیم با RoleChecker("admin") و Factory | Dependency پارامتردار |
انتخاب async def یا def | Dependencyهای async و sync |
تزریق Request، Response و request.state | تزریق درخواست و پاسخ |
کار OAuth2PasswordBearer و Security() | Dependency امنیتی |
تست با app.dependency_overrides | جایگزینی Dependency |
تفاوت Engine و Session و app.state | منابع Lifespan |
| محدودیت Session همزمان از 0.163.0 | max_concurrency |
| خطر وضعیت سراسری، Service locator و تزریق زیاد | ضدالگوها |
| مثال صفحهبندی، Authentication و Tenant | سه مثال کامل |
| کار FastAPI هنگام import و هر درخواست | سازوکار |
| خطاها و راه اصلاح | حل مسائل رایج |
انتخاب Depends یا ظرف (Container) | انتخاب |
| از Monolith تا سیستم توزیعشده | در معماری |
| اجرای عملی | آزمایشگاه |
| تطبیق Service container در Laravel | برای توسعهدهندگان PHP/Laravel |
| Constructor injection و wire و fx در Go | نگاه Go |
همهچیز در یک دقیقه (One minute)
واژگان. هر ردیف در فهرست مفاهیم باز میشود.
| اصطلاح | چیست | به زبان ساده | در قطعهکد (Snippet) |
|---|---|---|---|
| تزریق وابستگی (Dependency injection) | کد نیازش را اعلام میکند؛ Framework فراهم میکند | «بخواه، خودت نرو پیدا کن» | هر پارامتر Route با Depends |
| فراهمکننده (Dependable) | Callable دادهشده به Depends() | «تأمینکننده» | get_session، Pagination، require_admin |
| مصرفکننده (Dependant) | کدی که Dependency اعلام میکند | «مصرفکننده» | list_notes و نیز get_tenant_user |
| زیروابستگی (Sub-dependency) | Dependency یک Dependency | «فراهمکننده هم نیاز دارد» | نیاز get_session به get_engine |
| گراف وابستگی (Dependency graph) | همهٔ Dependableهای یک Path operation | «درختی که FastAPI حل میکند» | نمودار گراف |
| نام مستعار Annotated (Annotated alias) | X = Annotated[T, Depends(fn)] | «یک بار اعلام، چند بار استفاده» | SessionDep، CurrentUser، PageDep |
| Dependency مولد (Yield dependency) | Generator با Setup، yield value و Teardown | «قرض بگیر و پس بده» | get_session |
| Cache هر درخواست (Per-request cache) | یک مقدار بهازای هر Dependable در هر درخواست | «یک بار حل و سپس اشتراک» | oauth2_scheme |
| جایگزینی (Override) | app.dependency_overrides[original] = replacement | «تعویض گره در تست» | tests/test_overrides.py |
Dependency کجا وصل میشود و چه چیزی برمیگردد؟
| محل قرارگیری Dependency | نحو | مقدار به تابع داده میشود؟ | برای چه چیزی اجرا میشود | کاربرد معمول |
|---|---|---|---|---|
| پارامتر | user: Annotated[User, Depends(get_user)] | بله | همان Route | دادهٔ مصرفی Route |
| Decorator | @router.delete(..., dependencies=[Depends(require_admin)]) | نه | همان Route | نگهبان (Guard) و اثر جانبی |
| Router | APIRouter(dependencies=[Depends(verify_api_key)]) | نه | تمام Routeهای Router | Authentication گروهی |
| برنامه، سراسری | FastAPI(dependencies=[Depends(request_context)]) | نه | هر Route مطابق درخواست | شناسهٔ درخواست، Tenant و Audit |
| داخل Dependency دیگر | def b(a: Annotated[A, Depends(get_a)]) | بله، به b | هر جا b استفاده شود | ترکیب |
عمر اشیا (Lifetime). پاسخ «این شیء چقدر زنده است؟» محل ساختش را تعیین میکند.
| عمر | محل ساخت | مثال | مشترک میان | پاکسازی |
|---|---|---|---|---|
| Process، تکنمونه (Singleton) | lifespan پیش از yield | Engine و Pool آن، httpx.AsyncClient و تنظیمات | همهٔ درخواستهای یک Worker | lifespan پس از yield |
| درخواست | Dependency با Cache هر درخواست | Session، کاربر جاری، Tenant | همهٔ Dependantهای همان درخواست | Teardown پس از پاسخ |
| تابع | Depends(dep, scope="function") از 0.121.0+ | Session فقط برای بررسی کاربر | همان فراخوانی Path operation | پیش از ارسال پاسخ |
| فراخوانی | Depends(dep, use_cache=False) | مقدار تصادفی تازه یا شمارنده | هیچکس | در هر فراخوانی |
کد پس از yield چه زمانی اجرا میشود؟ جدول از یادداشتهای انتشار است؛ ردیف آخر اجرای واقعی 0.128.8 است.
| نسخهٔ FastAPI | زمان Teardown | نتیجه |
|---|---|---|
| قبل از 0.106.0 | پس از پاسخ و Background taskها | Task میتوانست از Session استفاده کند؛ استثنای پس از yield پاسخ را عوض نمیکرد |
| 0.106.0 (2023-12-25) | پیش از ارسال پاسخ | "Using resources from dependencies with yield in background tasks is no longer supported" |
| 0.110.0 (2024-02-24) | بدون تغییر | استثنایی که except بگیرد و دوباره پرتاب نکند دیگر منتقل نمیشود؛ باید raise کنید |
| 0.118.0 (2025-09-29) | دوباره پس از پاسخ | StreamingResponse هنگام ارسال تدریجی از Session استفاده میکند |
| 0.121.0 (2025-11-03) | پیشفرض پس از پاسخ؛ scope="function" پیش از آن | انتخاب مستقل برای هر Dependency |
| 0.128.8، اجرای واقعی | شروع پاسخ → Background task → Teardown به ترتیب c، b، a | tests/test_lifecycle.py |
چرا وجود دارد
هر نقطهٔ پایانی (Endpoint) در API واقعی به همان چند چیز نیاز دارد: Session پایگاه داده، کاربر احرازشده، Tenant، مقدارهای صفحهبندی (Pagination) و Client سرویس دیگر. بدون سازوکار مشترک، هر Route خودش Header میخواند، Session باز میکند و بستن آن را فراموش میکند، بررسی Authentication را کپی میکند و متغیرهای سراسری ماژول را import میکند؛ تست هم ناچار به تغییر پویا (Monkeypatch) میشود. DI نیازها را به اعلان تبدیل میکند. Route مینویسد session: SessionDep, user: TenantUser و Framework ساخت، ترتیب، عمر و پاکسازی را میداند. FastAPI دو ویژگی مهم دارد: حوزهٔ درخواست (Request scope)، یعنی Container سراسری اشیا ندارد و گراف با Cache مستقل در هر درخواست حل میشود؛ و اعلان از طریق امضا، یعنی Dependable تابع معمولی است و Query، Header و Cookie آن مثل ورودی Route اعتبارسنجی (Validation) و در سند OpenAPI ثبت میشوند.
| بدون DI در برنامهٔ قبل | با Depends در برنامهٔ بعد |
|---|---|
یک Session در سطح ماژول برای همهٔ درخواستها | یک Session برای هر درخواست از get_session، بستهشده در finally |
| یک شکست، Session مشترک را برای همه خراب میکند | Dependency بازگردانی و پاکسازی میکند؛ درخواست بعد سالم است |
| تجزیهٔ Authentication در هر Route کپی شده | get_current_user یک بار نوشته و از Alias استفاده میشود |
در int(request.query_params["page"]) مقدار "abc" خطای 500 میدهد | کلاس Pagination پاسخ 422 با خطای دقیق میدهد |
Route نیازش را از ServiceLocator میپرسد | نیازها در امضا روشناند |
| تست متغیر سراسری را تغییر میدهد و باید برگرداند | app.dependency_overrides[get_engine] = ... |
ورودیها در /openapi.json دیده نمیشوند | ورودی Dependency در هر عملیات مستند است |
تصویری از زندگی روزمره. اتاق عمل بیمارستان را ببینید. جراح، همان Path operation، خودش به داروخانه نمیرود، ابزار را استریل نمیکند و دستبند بیمار را نمیخواند؛ روی برنامه مینویسد «متخصص بیهوشی، سینی ابزار، خون O-negative و هویت تأییدشده». هماهنگکننده، یعنی FastAPI، پیش از شروع روز برنامهها را میخواند؛ همان زمان import. برای هر عمل نیازها را به ترتیب آماده میکند: هویت اول، چون سفارش خون به آن وابسته است. اگر دو نیاز به همان هویت احتیاج داشته باشند، بررسی برای آن عمل فقط یک بار انجام میشود؛ همان Cache هر درخواست. سینی ابزار قرضی است: ابتدا باز میشود، در yield تحویل داده میشود و بعد از خروج بیمار شمارش و برای استریل فرستاده میشود؛ Teardown پس از پاسخ. خود اتاق و تجهیزاتش، معادل Engine و Pool اتصال (Connection)، صبح یک بار آماده میشوند؛ Lifespan بهازای هر بیمار نیست. در تمرین آموزشی، هماهنگکننده بیمار را با مانکنی با همان دستبند عوض میکند؛ dependency_overrides بدون تغییر بقیهٔ برنامه.
سه بدفهمی رایج، پیش از شروع
- «
Dependsیک Container نگهدارندهٔ Singleton است.» بین درخواستها چیزی نگه نمیدارد. هر درخواست حل و Cache تازه دارد؛ شیء بلندعمر در Lifespan ساخته میشود و Dependency فقط آن را تحویل میدهد. - «کد بعد از
yieldپیش از رسیدن پاسخ اجرا میشود.» از 0.118.0 به بعد، پس از ارسال پاسخ و در اجرای واقعی حتی پس از Background task اجرا میشود.commit()آنجا وقتی شکست میخورد که Client پاسخ ۲۰۰ گرفته است. Commit را در Route انجام دهید یاscope="function"بگذارید. - «Override در تست همان Monkeypatch است.» FastAPI برای هر گره در دیکشنری جستوجو میکند. Override گره و Sub-dependencyهایش را جایگزین میکند و پارامترهای خودش مثل هر Dependency از درخواست خوانده میشوند.
از کجا آمده
این الگو از Frameworkهای وب Python قدیمیتر است. مقالهٔ «Inversion of Control Containers and the Dependency Injection pattern» نوشتهٔ Martin Fowler در ۲۳ ژانویهٔ ۲۰۰۴ آن را نامگذاری کرد. او در برابر Containerهای Java که خود را پیادهساز Inversion of Control مینامیدند پرسید: "what aspect of control are they inverting?". سپس نوشت: "Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection." مقایسهاش با Service Locator نیز روشن است: "With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class - hence the inversion of control."
اجزای Python بعدتر رسیدند. PEP 593 در Python 3.9، typing.Annotated را افزود: "This PEP adds an Annotated type to the typing module to decorate existing types with context-specific metadata". انتشار FastAPI 0.95.0 در ۲۰۲۳-۰۳-۱۸ میگوید "adds support for dependencies and parameters using Annotated and recommends its usage" و مشخصاً از "Annotated dependencies that are then shared by multiple path operation functions" یاد میکند. همانطور که جدول یکدقیقهای نشان میدهد، زمان Teardown چند بار تغییر کرد: 0.106.0 در ۲۰۲۳-۱۲-۲۵ آن را پیش از پاسخ برد؛ 0.110.0 در ۲۰۲۴-۰۲-۲۴ انتقال استثنای بلعیدهشده را متوقف کرد؛ 0.118.0 در ۲۰۲۵-۰۹-۲۹ دوباره آن را پس از پاسخ برد و 0.121.0 در ۲۰۲۵-۱۱-۰۳، scope را افزود. جریان OAuth2 password با Bearer token از 0.20.0 در ۲۰۱۹-۰۴-۲۷ پاسخ ۴۰۱ میدهد: "Upgrade Password flow using Bearer tokens to use the correct HTTP status code 401 UNAUTHORIZED, with WWW-Authenticate headers". نسخهٔ 0.122.0 در ۲۰۲۵-۱۱-۲۴ همین اصلاح را برای ابزارهای امنیتی دیگر انجام داد: "Use 401 status code in security classes when credentials are missing". صفحهٔ راهنما میگوید "Before FastAPI version 0.122.0, when the integrated security utilities returned an error to the client after a failed authentication, they used the HTTP status code 403 Forbidden" و مثالش HTTPBearer است. نسخهٔ 0.123.0 در ۲۰۲۵-۱۱-۳۰ Cache را اصلاح کرد: "Cache dependencies that don't use scopes and don't have sub-dependencies with scopes". بعد از نسخهٔ ثابت قطعهکدها، 0.137.0 در ۲۰۲۶-۰۶-۱۴ Routerها را بهجای کپی Routeها بهصورت درخت نگه داشت و "Dependencies per router" را از قابلیتهای ممکنشده دانست. نسخهٔ 0.144.0 در ۲۰۲۶-۱۰-۱۸، "WebSocket support to security dependencies" را افزود. نسخههای 0.162.5 و 0.162.7 در نوامبر ۲۰۲۶ پاکسازی Dependencyهای sync و async دارای yield هنگام لغو را اصلاح کردند؛ 0.163.0 در ۲۰۲۶-۱۱-۱۴ نیز Depends(max_concurrency=...) را افزود.
1 2004-01 Fowler: "Inversion of Control Containers and the Dependency Injection pattern"
2 2019-04 FastAPI 0.20.0: OAuth2 password bearer flow answers 401 + WWW-Authenticate
3 2020-10 Python 3.9 released with typing.Annotated (PEP 593, Python-Version 3.9)
4 2023-03 FastAPI 0.95.0: Annotated dependencies recommended (SessionDep-style aliases)
5 2023-12 0.106.0: yield teardown before the response; no yielded resources in background tasks
6 2024-02 0.110.0: except without raise is no longer forwarded (must re-raise)
7 2025-09 0.118.0: yield teardown after the response again (StreamingResponse)
8 2025-11 0.121.0 Depends(scope="function"); 0.122.0 HTTPBearer & co. 401 instead of 403; 0.123.0 cache fix
9 2026-02 0.128.8: last release for Python 3.9 (the snippet pin)
10 2026-06 0.137.0: router tree, "dependencies per router" enabled
11 2026-11 0.144 WebSocket security deps; 0.162.x cancellation cleanup; 0.163.0 max_concurrencyPython
قبل (Before)
یک API یادداشت بدون تزریق وابستگی (Dependency injection). یک Session هنگام import ساخته و میان همهٔ درخواستها مشترک میشود؛ ServiceLocator آن و جدول Token را تحویل میدهد. هر Route خودش Authorization، X-Tenant-ID و مقدارهای صفحه را میخواند و بعد از شکست هیچ بازگردانی (Rollback) انجام نمیشود.
"""The Before app: no dependency injection. Works on a quiet day; every route repeats the plumbing.
Bugs on purpose:
- one module-level Session shared by every request (global mutable state);
- a service locator: routes ask a registry for what they need;
- auth, tenant and pagination parsing copied into each route;
- no teardown: nothing rolls back after a failed request;
- tests can only swap things by mutating module globals.
"""
from __future__ import annotations
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.db import Note, create_schema_and_seed, make_engine
engine = make_engine("sqlite://") # created at import time, even in tests
create_schema_and_seed(engine)
SESSION = Session(engine) # one Session for the whole process
class ServiceLocator:
"""Anti-pattern: every caller depends on the locator and hides what it really needs."""
_services: dict = {}
@classmethod
def register(cls, name: str, obj: object) -> None:
cls._services[name] = obj
@classmethod
def get(cls, name: str):
return cls._services[name]
ServiceLocator.register("db", SESSION)
ServiceLocator.register("tokens", {"alice-token": ("alice", "acme"), "bob-token": ("bob", "acme")})
app = FastAPI(title="Notes API (before)")
@app.get("/notes")
def list_notes(request: Request):
auth = request.headers.get("authorization", "") # copy 1 of the auth code
user = ServiceLocator.get("tokens").get(auth.removeprefix("Bearer "))
if user is None:
return JSONResponse({"error": "unauthorized"}, status_code=401)
tenant = request.headers.get("x-tenant-id", "")
page = int(request.query_params.get("page", "1")) # copy 1 of pagination; "abc" -> 500
size = int(request.query_params.get("size", "20"))
db: Session = ServiceLocator.get("db")
rows = db.scalars(
select(Note).where(Note.tenant_id == tenant).order_by(Note.id).limit(size).offset((page - 1) * size)
).all()
return [{"id": n.id, "title": n.title, "owner": n.owner} for n in rows]
@app.post("/notes", status_code=201)
async def create_note(request: Request):
auth = request.headers.get("authorization", "") # copy 2 of the auth code
user = ServiceLocator.get("tokens").get(auth.removeprefix("Bearer "))
if user is None:
return JSONResponse({"error": "unauthorized"}, status_code=401)
body = await request.json()
db: Session = ServiceLocator.get("db")
note = Note(tenant_id=user[1], title=body["title"], owner=user[0])
db.add(note)
db.commit() # an IntegrityError here leaves the shared Session needing a rollback
return {"id": note.id, "title": note.title, "owner": note.owner}تستها خطاها را دقیق مشخص میکنند. مهمترین مورد: درخواست ناقض قید یکتایی (Unique constraint)، Session مشترک را در تراکنش (Transaction) شکستخورده باقی میگذارد و درخواست بعدی و نامرتبط با PendingRollbackError شکست میخورد؛ این نتیجهٔ اجرای واقعی است.
"""Pins down the bugs of app/before.py (no dependency injection)."""
from fastapi.testclient import TestClient
from app import before
A = {"Authorization": "Bearer alice-token", "X-Tenant-ID": "acme"}
def test_one_session_for_every_request():
assert before.ServiceLocator.get("db") is before.SESSION
def test_bad_page_is_a_500_not_a_422():
c = TestClient(before.app, raise_server_exceptions=False)
assert c.get("/notes?page=abc", headers=A).status_code == 500
def test_one_failed_request_poisons_the_shared_session():
c = TestClient(before.app, raise_server_exceptions=False)
assert c.get("/notes?size=1", headers=A).status_code == 200
# duplicate (tenant_id, title): IntegrityError, nobody rolls back
assert c.post("/notes", json={"title": "acme note 1"}, headers=A).status_code == 500
# an unrelated, valid request now fails too: PendingRollbackError
assert c.get("/notes?size=1", headers=A).status_code == 500
before.SESSION.rollback() # the manual cleanup a yield dependency would have done
def test_swapping_a_service_means_mutating_a_global():
c = TestClient(before.app)
saved = before.ServiceLocator.get("tokens")
before.ServiceLocator.register("tokens", {"t": ("tess", "acme")})
try:
r = c.get("/notes?size=1", headers={"Authorization": "Bearer t", "X-Tenant-ID": "acme"})
assert r.status_code == 200
finally:
before.ServiceLocator.register("tokens", saved) # forget this and other tests break
def test_errors_are_ad_hoc_bodies_and_not_in_openapi():
c = TestClient(before.app)
r = c.get("/notes")
assert r.status_code == 401 and r.json() == {"error": "unauthorized"}
params = c.get("/openapi.json").json()["paths"]["/notes"]["get"].get("parameters", [])
assert params == [] # page, size, tenant, auth: invisible to clientsبعد (After)
مدلها و کارخانهٔ Engine. Engine یک بار در هر Process ساخته میشود. SQLite درونحافظهای به StaticPool و check_same_thread=False نیاز دارد، چون Dependencyهای sync و Routeهای def در Threadهای Worker اجرا میشوند:
"""SQLAlchemy 2 models and the engine factory used by the lifespan."""
from __future__ import annotations
from sqlalchemy import ForeignKey, String, UniqueConstraint, create_engine
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.pool import StaticPool
class Base(DeclarativeBase):
pass
class Tenant(Base):
__tablename__ = "tenants"
id: Mapped[str] = mapped_column(String(32), primary_key=True)
name: Mapped[str] = mapped_column(String(100))
class Note(Base):
__tablename__ = "notes"
__table_args__ = (UniqueConstraint("tenant_id", "title"),)
id: Mapped[int] = mapped_column(primary_key=True)
tenant_id: Mapped[str] = mapped_column(ForeignKey("tenants.id"), index=True)
title: Mapped[str] = mapped_column(String(120))
owner: Mapped[str] = mapped_column(String(50))
def make_engine(url: str = "sqlite://", echo: bool = False) -> Engine:
"""One engine (and its connection pool) per process: created in the lifespan, never per request.
SQLite in memory needs StaticPool (one shared connection) and check_same_thread=False,
because sync dependencies and `def` routes run on AnyIO worker threads.
"""
if url.startswith("sqlite"):
return create_engine(
url,
echo=echo,
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
return create_engine(url, echo=echo, pool_size=10, max_overflow=5, pool_pre_ping=True)
def create_schema_and_seed(engine: Engine) -> None:
Base.metadata.create_all(engine)
with Session(engine) as s:
if s.get(Tenant, "acme") is None:
s.add_all([Tenant(id="acme", name="Acme"), Tenant(id="globex", name="Globex")])
s.add_all(
[Note(tenant_id="acme", title=f"acme note {i}", owner="alice") for i in range(1, 6)]
+ [Note(tenant_id="globex", title="globex note 1", owner="carol")]
)
s.commit()همهٔ Dependencyها در یک ماژول، معمولاً app/dependencies.py، قرار دارند: Session دارای yield، کلاس Pagination، Header مربوط به Tenant، OAuth2PasswordBearer و get_current_user با Scopeها، بررسی Tenant ساختهشده از دو Sub-dependency، کلاس Callable به نام RoleChecker، کارخانهٔ Closure به نام requires_feature، Guard مربوط به Router با verify_api_key و Dependency سراسری request_context. این ماژول عمداً from __future__ import annotations ندارد؛ دلیل:
"""Every dependency of the After app, in one module (the usual app/dependencies.py).
No `from __future__ import annotations` here: FastAPI resolves string annotations with the
function's __globals__, and a class or a callable instance has none (see app/future_gotcha.py).
"""
import uuid
from collections.abc import Iterator
from typing import Annotated, Optional
from fastapi import Depends, Header, HTTPException, Query, Request, Response, Security, status
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
from pydantic import BaseModel
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session
# ---------- resources: engine from the lifespan, one Session per request ----------
def get_engine(request: Request) -> Engine:
# Created once in the lifespan and stored on app.state: a process-wide singleton.
return request.app.state.engine
def get_session(engine: Annotated[Engine, Depends(get_engine)]) -> Iterator[Session]:
# A yield dependency: code before `yield` is setup, code after it is teardown.
session = Session(engine)
try:
yield session # the value injected into the route
except Exception:
session.rollback() # an exception raised in the route arrives here
raise # always re-raise (FastAPI 0.110+ does not do it for you)
finally:
session.close() # runs on success and on failure
SessionDep = Annotated[Session, Depends(get_session)] # the Annotated alias
# ---------- a class dependency: pagination ----------
class Pagination:
def __init__(
self,
page: Annotated[int, Query(ge=1, description="1-based page number")] = 1,
size: Annotated[int, Query(ge=1, le=100)] = 20,
) -> None:
self.page = page
self.size = size
@property
def offset(self) -> int:
return (self.page - 1) * self.size
PageDep = Annotated[Pagination, Depends()] # Depends() with no argument: "call the annotated class"
# ---------- tenant from a header ----------
def get_tenant(
x_tenant_id: Annotated[str, Header(pattern=r"^[a-z][a-z0-9-]{1,31}$")],
) -> str:
return x_tenant_id
TenantDep = Annotated[str, Depends(get_tenant)]
# ---------- authentication: OAuth2PasswordBearer + get_current_user ----------
class User(BaseModel):
name: str
tenant: str
roles: list[str] = []
scopes: list[str] = []
# Fake token store; the real token check (JWT, hashing) is the auth chapter's job.
FAKE_TOKENS = {
"alice-token": User(name="alice", tenant="acme", roles=["admin"], scopes=["notes:read", "notes:write"]),
"bob-token": User(name="bob", tenant="acme", roles=[], scopes=["notes:read"]),
"carol-token": User(name="carol", tenant="globex", roles=[], scopes=["notes:read", "notes:write"]),
}
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="token",
scopes={"notes:read": "Read notes", "notes:write": "Create notes"},
)
def get_current_user(
security_scopes: SecurityScopes,
token: Annotated[str, Depends(oauth2_scheme)], # sub-dependency: the bearer token
) -> User:
user = FAKE_TOKENS.get(token)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"},
)
missing = [s for s in security_scopes.scopes if s not in user.scopes]
if missing:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Missing scope: {' '.join(missing)}",
headers={"WWW-Authenticate": f'Bearer scope="{security_scopes.scope_str}"'},
)
return user
CurrentUser = Annotated[User, Security(get_current_user, scopes=["notes:read"])]
WriterUser = Annotated[User, Security(get_current_user, scopes=["notes:write"])]
def get_tenant_user(user: CurrentUser, tenant: TenantDep) -> User:
# Sub-dependency graph: tenant header + authenticated user -> a user allowed in this tenant.
if user.tenant != tenant:
raise HTTPException(status.HTTP_403_FORBIDDEN, "User does not belong to this tenant")
return user
TenantUser = Annotated[User, Depends(get_tenant_user)]
# ---------- parameterised dependencies ----------
class RoleChecker:
"""A callable class: __init__ takes our parameters, __call__ is what FastAPI analyses."""
def __init__(self, role: str) -> None:
self.role = role
def __call__(self, user: CurrentUser) -> User:
if self.role not in user.roles:
raise HTTPException(status.HTTP_403_FORBIDDEN, f"Requires role {self.role}")
return user
require_admin = RoleChecker("admin") # module-level instance: the key for dependency_overrides
def requires_feature(flag: str):
"""A closure factory: returns a new dependency function per flag."""
def check(request: Request) -> None:
if not request.app.state.features.get(flag, False):
raise HTTPException(status.HTTP_404_NOT_FOUND, "Not Found")
check.__name__ = f"requires_feature_{flag}"
return check
# ---------- decorator / router / global dependencies (no return value used) ----------
def verify_api_key(x_api_key: Annotated[str, Header()]) -> None:
if x_api_key != "admin-key":
raise HTTPException(status.HTTP_403_FORBIDDEN, "Bad API key")
def request_context(
request: Request,
response: Response,
x_request_id: Annotated[Optional[str], Header()] = None,
) -> None:
# Global dependency: Request and Response injection, request.state for per-request data.
rid = x_request_id or uuid.uuid4().hex
request.state.request_id = rid
response.headers["X-Request-ID"] = ridبرنامه: Lifespan مالک Engine و Lifespan state است. Routeها Alias اعلام میکنند. Router مدیریت، Dependency در سطح Router دارد؛ Route حذف، Dependency Decorator دارد؛ برنامه هم Dependency سراسری دارد. create_app() اجازه میدهد هر تست برنامهٔ تازه بسازد:
"""The After app: resources from the lifespan, per-request dependencies, router and global dependencies."""
from __future__ import annotations
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import APIRouter, BackgroundTasks, Depends, FastAPI, HTTPException, Request, status
from pydantic import BaseModel
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError
from app.db import Note, create_schema_and_seed, make_engine
from app.deps import (
PageDep, SessionDep, TenantDep, TenantUser, WriterUser,
request_context, require_admin, requires_feature, verify_api_key,
)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[dict]:
# Process-wide resources: created once per worker process, before the first request.
engine = make_engine(os.environ.get("DATABASE_URL", "sqlite://"))
create_schema_and_seed(engine)
app.state.engine = engine
app.state.features = {"beta": False}
# Lifespan state: Starlette copies this dict (shallow) into every request.state.
yield {"audit_log": []}
engine.dispose()
class NoteIn(BaseModel):
title: str
class NoteOut(BaseModel):
id: int
title: str
owner: str
def write_audit(log: list, request_id: str, note_id: int) -> None:
# A background task gets plain values (ids), never the request's Session.
log.append(f"{request_id} created note {note_id}")
notes = APIRouter(prefix="/notes", tags=["notes"])
@notes.get("", response_model=list[NoteOut])
def list_notes(session: SessionDep, tenant: TenantDep, page: PageDep, user: TenantUser):
stmt = (
select(Note)
.where(Note.tenant_id == tenant)
.order_by(Note.id)
.limit(page.size)
.offset(page.offset)
)
return session.scalars(stmt).all()
@notes.post("", response_model=NoteOut, status_code=status.HTTP_201_CREATED)
def create_note(
body: NoteIn,
session: SessionDep,
user: WriterUser,
tenant_user: TenantUser,
request: Request,
tasks: BackgroundTasks,
):
note = Note(tenant_id=tenant_user.tenant, title=body.title, owner=user.name)
session.add(note)
try:
session.commit() # commit inside the route: the client sees the result of the commit
except IntegrityError:
session.rollback()
raise HTTPException(status.HTTP_409_CONFLICT, "A note with this title exists")
tasks.add_task(write_audit, request.state.audit_log, request.state.request_id, note.id)
return note
@notes.delete("/{note_id}", status_code=status.HTTP_204_NO_CONTENT, dependencies=[Depends(require_admin)])
def delete_note(note_id: int, session: SessionDep, user: TenantUser) -> None:
note = session.get(Note, note_id)
if note is None or note.tenant_id != user.tenant:
raise HTTPException(status.HTTP_404_NOT_FOUND, "Note not found")
session.delete(note)
session.commit()
admin = APIRouter(prefix="/admin", tags=["admin"], dependencies=[Depends(verify_api_key)])
@admin.get("/stats")
def stats(session: SessionDep) -> dict:
rows = session.execute(select(Note.tenant_id, func.count()).group_by(Note.tenant_id)).all()
return {tenant: count for tenant, count in rows}
@admin.get("/audit")
def audit(request: Request) -> list:
return request.state.audit_log
misc = APIRouter(tags=["misc"])
@misc.get("/beta/summary", dependencies=[Depends(requires_feature("beta"))])
def beta_summary() -> dict:
return {"beta": True}
@misc.get("/whoami")
def whoami(user: TenantUser, request: Request) -> dict:
return {"name": user.name, "tenant": user.tenant, "request_id": request.state.request_id}
def create_app() -> FastAPI:
"""An app factory: every test can build a fresh app with its own overrides and lifespan."""
app = FastAPI(
title="Notes API",
lifespan=lifespan,
dependencies=[Depends(request_context)], # global: runs for every matched route
)
app.include_router(notes)
app.include_router(admin)
app.include_router(misc)
return app
app = create_app()Fixtureها برای هر تست برنامهٔ تازه میسازند و بعد Overrideها را پاک میکنند:
import pytest
from fastapi.testclient import TestClient
from app.main import create_app
ALICE = {"Authorization": "Bearer alice-token", "X-Tenant-ID": "acme"} # admin, read + write
BOB = {"Authorization": "Bearer bob-token", "X-Tenant-ID": "acme"} # read only
@pytest.fixture
def app():
app = create_app()
yield app
app.dependency_overrides.clear() # never leak an override into the next test
@pytest.fixture
def client(app):
with TestClient(app) as c: # `with` runs the lifespan: engine, schema, seed
yield cتستها تکتک Dependencyها را طی میکنند: Pagination، پاسخهای ۴۰۱ و ۴۰۳، Scope، Tenant، Commit در Route، کلاس Callable، Guard مربوط به Router، پرچم قابلیت (Feature flag)، Dependency سراسری، گمشدن Header روی خطا و کلید Cache شامل Scopeها:
"""The After app: each dependency doing its job."""
from tests.conftest import ALICE, BOB
def test_pagination_class_dependency(client):
r = client.get("/notes?page=2&size=2", headers=ALICE)
assert r.status_code == 200
assert [n["id"] for n in r.json()] == [3, 4]
def test_pagination_validation_is_a_422(client):
r = client.get("/notes?page=0", headers=ALICE)
assert r.status_code == 422
assert r.json()["detail"][0]["loc"] == ["query", "page"]
def test_missing_bearer_token_is_401(client):
r = client.get("/notes", headers={"X-Tenant-ID": "acme"})
assert r.status_code == 401 # OAuth2PasswordBearer: 401 since FastAPI 0.20.0
assert r.json() == {"detail": "Not authenticated"}
assert r.headers["www-authenticate"] == "Bearer"
def test_invalid_token_is_401_from_get_current_user(client):
r = client.get("/notes", headers={"Authorization": "Bearer nope", "X-Tenant-ID": "acme"})
assert (r.status_code, r.json()["detail"]) == (401, "Invalid token")
def test_missing_scope_is_403(client):
r = client.post("/notes", json={"title": "x"}, headers=BOB)
assert r.status_code == 403
assert r.headers["www-authenticate"] == 'Bearer scope="notes:write"'
def test_tenant_header_validated_and_matched(client):
assert client.get("/notes", headers={**ALICE, "X-Tenant-ID": "Bad_Tenant"}).status_code == 422
r = client.get("/notes", headers={**ALICE, "X-Tenant-ID": "globex"})
assert (r.status_code, r.json()["detail"]) == (403, "User does not belong to this tenant")
def test_create_commits_in_route_and_background_task_gets_ids(client):
r = client.post("/notes", json={"title": "new"}, headers={**ALICE, "X-Request-ID": "req-1"})
assert r.status_code == 201 and r.headers["x-request-id"] == "req-1"
assert client.post("/notes", json={"title": "new"}, headers=ALICE).status_code == 409
# the Session survived the IntegrityError: the next request works
assert client.get("/notes?size=1", headers=ALICE).status_code == 200
audit = client.get("/admin/audit", headers={"X-API-Key": "admin-key"}).json()
assert audit == [f"req-1 created note {r.json()['id']}"]
def test_callable_class_role_checker(client):
assert client.delete("/notes/1", headers=BOB).status_code == 403
assert client.delete("/notes/1", headers=ALICE).status_code == 204
def test_router_dependency_guards_every_admin_route(client):
assert client.get("/admin/stats").status_code == 422 # header missing
assert client.get("/admin/stats", headers={"X-API-Key": "x"}).status_code == 403
r = client.get("/admin/stats", headers={"X-API-Key": "admin-key"})
assert r.json() == {"acme": 5, "globex": 1}
def test_closure_factory_feature_flag(client, app):
assert client.get("/beta/summary").status_code == 404
app.state.features["beta"] = True
assert client.get("/beta/summary").json() == {"beta": True}
def test_global_dependency_sets_request_state_and_header(client):
r = client.get("/whoami", headers=ALICE)
assert r.json()["request_id"] == r.headers["x-request-id"]
def test_header_set_on_injected_response_is_lost_on_httpexception(client):
# request_context ran and set X-Request-ID on the injected Response,
# but the 401 is a new response built by the exception handler.
r = client.get("/whoami", headers={"X-Tenant-ID": "acme", "X-Request-ID": "r-9"})
assert r.status_code == 401 and "x-request-id" not in r.headers
def test_global_dependency_does_not_run_for_unmatched_paths(client):
r = client.get("/nope")
assert r.status_code == 404 and "x-request-id" not in r.headers
def test_lifespan_state_is_per_app(app):
from fastapi.testclient import TestClient
with TestClient(app) as c:
c.post("/notes", json={"title": "one"}, headers=ALICE)
assert len(c.get("/admin/audit", headers={"X-API-Key": "admin-key"}).json()) == 1
with TestClient(app) as c: # a new lifespan: new engine, new audit_log
assert c.get("/admin/audit", headers={"X-API-Key": "admin-key"}).json() == []
class CountingTokens(dict):
calls = 0
def get(self, key, default=None):
CountingTokens.calls += 1
return super().get(key, default)
def test_cache_key_includes_security_scopes(client, monkeypatch):
import app.deps as deps
monkeypatch.setattr(deps, "FAKE_TOKENS", CountingTokens(deps.FAKE_TOKENS))
CountingTokens.calls = 0
client.delete("/notes/2", headers=ALICE) # require_admin + TenantUser: same scopes
assert CountingTokens.calls == 1 # get_current_user ran once
CountingTokens.calls = 0
client.post("/notes", json={"title": "t"}, headers=ALICE) # notes:write and notes:read
assert CountingTokens.calls == 2 # two cache keys -> two calls
def test_security_scheme_is_cached_per_scope_set(client, monkeypatch):
from fastapi.security import OAuth2PasswordBearer
seen = []
original = OAuth2PasswordBearer.__call__
async def counting(self, request):
seen.append(1)
return await original(self, request)
monkeypatch.setattr(OAuth2PasswordBearer, "__call__", counting)
client.get("/notes", headers=ALICE) # notes:read only
assert len(seen) == 1
seen.clear()
client.post("/notes", json={"title": "s"}, headers=ALICE) # notes:write branch + notes:read branch
assert len(seen) == 2 # the scheme's cache key includes the scopesOverrideها، از جمله جایگزینی عمیق Engine، جایگزینی با پارامترهای مستقل خودش و دام کلیدِ نمونه در برابر کلاس:
"""app.dependency_overrides: replace a dependency anywhere in the graph, for one test."""
from typing import Annotated
from fastapi import Query
from fastapi.testclient import TestClient
from app.db import create_schema_and_seed, make_engine
from app.deps import (
RoleChecker, User, get_current_user, get_engine, get_tenant,
request_context, require_admin, verify_api_key,
)
TESTER = User(name="tester", tenant="acme", roles=[], scopes=["notes:read", "notes:write"])
def test_override_skips_the_original_and_its_sub_dependencies(app, client):
# get_current_user normally needs oauth2_scheme -> an Authorization header.
app.dependency_overrides[get_current_user] = lambda: TESTER
r = client.get("/whoami", headers={"X-Tenant-ID": "acme"})
assert r.status_code == 200 and r.json()["name"] == "tester"
def test_override_a_deep_sub_dependency_the_engine(app, tmp_path):
engine = make_engine(f"sqlite:///{tmp_path / 'test.db'}")
create_schema_and_seed(engine)
app.dependency_overrides[get_engine] = lambda: engine # get_session still runs, on our engine
with TestClient(app) as c:
r = c.post("/notes", json={"title": "on disk"}, headers={"Authorization": "Bearer alice-token", "X-Tenant-ID": "acme"})
assert r.status_code == 201
with engine.connect() as conn:
assert conn.exec_driver_sql("SELECT count(*) FROM notes WHERE title = 'on disk'").scalar() == 1
def test_override_can_declare_its_own_parameters(app, client):
def tenant_from_query(t: Annotated[str, Query()] = "acme") -> str:
return t
app.dependency_overrides[get_tenant] = tenant_from_query
r = client.get("/notes?size=1&t=acme", headers={"Authorization": "Bearer alice-token"})
assert r.status_code == 200 # no X-Tenant-ID header needed any more
def test_parameterised_instance_is_the_key_not_the_class(app, client):
app.dependency_overrides[get_current_user] = lambda: TESTER # not an admin
assert client.delete("/notes/1", headers={"X-Tenant-ID": "acme"}).status_code == 403
app.dependency_overrides[RoleChecker] = lambda: None # wrong key: ignored
assert client.delete("/notes/1", headers={"X-Tenant-ID": "acme"}).status_code == 403
app.dependency_overrides[require_admin] = lambda: None # the instance used in the route
assert client.delete("/notes/1", headers={"X-Tenant-ID": "acme"}).status_code == 204
def test_router_and_global_dependencies_can_be_overridden(app, client):
app.dependency_overrides[verify_api_key] = lambda: None
app.dependency_overrides[request_context] = lambda: None
r = client.get("/admin/stats")
assert r.status_code == 200 and "x-request-id" not in r.headers
def test_clear_restores_the_real_graph(app, client):
app.dependency_overrides[verify_api_key] = lambda: None
assert client.get("/admin/stats").status_code == 200
app.dependency_overrides.clear()
assert client.get("/admin/stats").status_code == 422برنامهٔ کاوشگر ترتیب رویدادهای یک درخواست را ثبت میکند. میانافزار (Middleware) خالص ASGI لحظهٔ خروج وضعیت پاسخ از برنامه را Log میکند:
"""A probe app that records, in order, what the dependency system does during one request."""
from __future__ import annotations
import asyncio
import threading
from collections.abc import AsyncIterator, Iterator
from typing import Annotated
from fastapi import APIRouter, BackgroundTasks, Depends, FastAPI, HTTPException, Query
EVENTS: list[str] = []
CALLS: dict[str, int] = {}
def log(event: str) -> None:
EVENTS.append(event)
class RecordSend:
"""Pure ASGI middleware: logs the moment the response status line leaves the app."""
def __init__(self, app) -> None:
self.app = app
async def __call__(self, scope, receive, send):
async def wrapped(message):
if message["type"] == "http.response.start":
log(f"response.start {message['status']}")
await send(message)
await self.app(scope, receive, wrapped)
# ---------- resolution order: app, router, decorator, parameter ----------
def app_dep() -> None:
log("app dependency")
def router_dep() -> None:
log("router dependency")
def decorator_dep() -> None:
log("decorator dependency")
def param_dep() -> str:
log("parameter dependency")
return "value"
app = FastAPI(dependencies=[Depends(app_dep)])
app.add_middleware(RecordSend)
router = APIRouter(dependencies=[Depends(router_dep)])
@router.get("/order", dependencies=[Depends(decorator_dep)])
def order(v: Annotated[str, Depends(param_dep)]) -> dict:
log("route")
return {"v": v}
# ---------- caching: one call per request unless use_cache=False ----------
def counted() -> int:
CALLS["counted"] = CALLS.get("counted", 0) + 1
return CALLS["counted"]
def left(n: Annotated[int, Depends(counted)]) -> int:
return n
def right(n: Annotated[int, Depends(counted)]) -> int:
return n
@app.get("/cache")
def cache(a: Annotated[int, Depends(left)], b: Annotated[int, Depends(right)]) -> dict:
return {"left": a, "right": b, "calls": CALLS["counted"]}
@app.get("/nocache")
def nocache(
a: Annotated[int, Depends(counted)],
b: Annotated[int, Depends(counted, use_cache=False)],
) -> dict:
return {"a": a, "b": b, "calls": CALLS["counted"]}
@app.get("/nocache-first")
def nocache_first(
a: Annotated[int, Depends(counted, use_cache=False)], # runs, and its result is stored in the cache
b: Annotated[int, Depends(counted)], # cache hit: reuses a's value
) -> dict:
return {"a": a, "b": b, "calls": CALLS["counted"]}
# ---------- validation errors do not stop sibling dependencies ----------
def side_effect() -> None:
log("side effect ran")
def needs_int(n: Annotated[int, Query()]) -> int:
return n
@app.get("/sibling")
def sibling(n: Annotated[int, Depends(needs_int)], _: Annotated[None, Depends(side_effect)]) -> dict:
log("route")
return {"n": n}
def guarded_side_effect(n: Annotated[int, Depends(needs_int)]) -> int:
# Depends on the validated input: not called when that input fails validation.
log("guarded side effect ran")
return n
@app.get("/guarded")
def guarded(n: Annotated[int, Depends(guarded_side_effect)]) -> dict:
return {"n": n}
# ---------- yield: setup, teardown order, response before teardown ----------
def dep_a() -> Iterator[str]:
log("a setup")
try:
yield "a"
finally:
log("a teardown")
def dep_b(a: Annotated[str, Depends(dep_a)]) -> Iterator[str]:
log("b setup")
try:
yield a + "b"
finally:
log("b teardown")
async def dep_c(b: Annotated[str, Depends(dep_b)]) -> AsyncIterator[str]:
log("c setup")
try:
yield b + "c"
finally:
log("c teardown")
def task(name: str) -> None:
log(f"background task {name}")
@app.get("/teardown")
def teardown(c: Annotated[str, Depends(dep_c)], tasks: BackgroundTasks) -> dict:
log("route")
tasks.add_task(task, "ran")
return {"chain": c}
def early() -> Iterator[str]:
log("function-scope setup")
try:
yield "x"
finally:
log("function-scope teardown")
@app.get("/function-scope")
def function_scope(x: Annotated[str, Depends(early, scope="function")]) -> dict:
log("route")
return {"x": x}
# ---------- exceptions inside yield dependencies ----------
class OwnerError(Exception):
pass
def translating() -> Iterator[str]:
try:
yield "rick"
except OwnerError as e:
log("translating caught OwnerError")
raise HTTPException(status_code=400, detail=f"Owner error: {e}")
@app.get("/translate")
def translate(user: Annotated[str, Depends(translating)]) -> dict:
raise OwnerError(user)
def swallowing() -> Iterator[str]:
try:
yield "rick"
except ValueError:
log("swallowing caught ValueError and did not re-raise")
@app.get("/swallow")
def swallow(user: Annotated[str, Depends(swallowing)]) -> dict:
raise ValueError("boom")
def raises_in_setup() -> str:
raise HTTPException(status_code=403, detail="denied in dependency")
@app.get("/denied")
def denied(x: Annotated[str, Depends(raises_in_setup)]) -> dict:
log("route must not run")
return {}
# ---------- which thread runs what ----------
def sync_dep() -> str:
return threading.current_thread().name
async def async_dep() -> str:
await asyncio.sleep(0)
return threading.current_thread().name
@app.get("/threads")
async def threads(s: Annotated[str, Depends(sync_dep)], a: Annotated[str, Depends(async_dep)]) -> dict:
return {"sync_dependency": s, "async_dependency": a, "async_route": threading.current_thread().name}
app.include_router(router)"""What the dependency system does, in order, during one request (FastAPI 0.128.8)."""
import pytest
from fastapi.testclient import TestClient
from app import lifecycle as L
@pytest.fixture
def c():
L.EVENTS.clear()
L.CALLS.clear()
return TestClient(L.app, raise_server_exceptions=False)
def test_resolution_order_app_router_decorator_parameter(c):
c.get("/order")
assert L.EVENTS == [
"app dependency", "router dependency", "decorator dependency",
"parameter dependency", "route", "response.start 200",
]
def test_cached_per_request(c):
assert c.get("/cache").json() == {"left": 1, "right": 1, "calls": 1}
assert c.get("/cache").json()["calls"] == 2 # new request, new cache
def test_use_cache_false_calls_again(c):
assert c.get("/nocache").json() == {"a": 1, "b": 2, "calls": 2}
def test_uncached_declaration_first_feeds_the_cache(c):
# order matters: the use_cache=False call runs first and its value is cached for Depends(counted)
assert c.get("/nocache-first").json() == {"a": 1, "b": 1, "calls": 1}
def test_validation_error_does_not_stop_a_sibling_side_effect(c):
r = c.get("/sibling?n=abc")
assert r.status_code == 422
assert "side effect ran" in L.EVENTS and "route" not in L.EVENTS
def test_side_effect_that_depends_on_the_input_is_skipped(c):
assert c.get("/guarded?n=abc").status_code == 422
assert "guarded side effect ran" not in L.EVENTS
assert c.get("/guarded?n=3").json() == {"n": 3}
def test_teardown_after_response_and_background_tasks_in_reverse_order(c):
assert c.get("/teardown").json() == {"chain": "abc"}
assert L.EVENTS == [
"app dependency", "a setup", "b setup", "c setup", "route",
"response.start 200", "background task ran",
"c teardown", "b teardown", "a teardown",
]
def test_scope_function_tears_down_before_the_response(c):
c.get("/function-scope")
assert L.EVENTS[-3:] == ["route", "function-scope teardown", "response.start 200"]
def test_exception_translated_in_yield_dependency(c):
r = c.get("/translate")
assert (r.status_code, r.json()) == (400, {"detail": "Owner error: rick"})
def test_swallowed_exception_is_still_a_500(c):
r = c.get("/swallow")
assert r.status_code == 500
assert "swallowing caught ValueError and did not re-raise" in L.EVENTS
def test_httpexception_in_setup_stops_before_the_route(c):
r = c.get("/denied")
assert r.status_code == 403 and "route must not run" not in L.EVENTS
def test_sync_dependency_runs_in_the_threadpool(c):
t = c.get("/threads").json()
assert t["sync_dependency"].startswith("AnyIO worker thread")
assert t["async_dependency"] == t["async_route"] # on the event loop threadآنچه Dependencyها وارد طرحواره (Schema) در OpenAPI میکنند، و یک دام واقعی که تست آن را تثبیت کرده است:
"""Dependencies document themselves: their parameters and security schemes reach OpenAPI."""
from app.main import create_app
def schema():
return create_app().openapi()
def test_dependency_parameters_appear_on_the_operation():
params = {(p["in"], p["name"]) for p in schema()["paths"]["/notes"]["get"]["parameters"]}
assert {("query", "page"), ("query", "size"), ("header", "x-tenant-id"), ("header", "x-request-id")} <= params
def test_router_dependency_header_on_every_admin_route():
paths = schema()["paths"]
for path in ("/admin/stats", "/admin/audit"):
names = {p["name"] for p in paths[path]["get"]["parameters"]}
assert "x-api-key" in names
def test_oauth2_scheme_and_scopes():
s = schema()
scheme = s["components"]["securitySchemes"]["OAuth2PasswordBearer"]
assert scheme["flows"]["password"]["tokenUrl"] == "token"
assert set(scheme["flows"]["password"]["scopes"]) == {"notes:read", "notes:write"}
# Security(..., scopes=[...]) declarations are merged per operation
assert s["paths"]["/notes"]["get"]["security"] == [{"OAuth2PasswordBearer": ["notes:read"]}]
assert s["paths"]["/notes"]["post"]["security"] == [{"OAuth2PasswordBearer": ["notes:write", "notes:read"]}]"""Gotcha on FastAPI 0.128.8: a class dependency in a module with postponed annotations.
FastAPI evaluates string annotations with `call.__globals__`. Functions have it; a class
(its __init__ is inspected through the class) and a callable instance do not, so the
strings stay ForwardRefs and the request fails with PydanticUserError (500).
"""
from __future__ import annotations
from typing import Annotated
from fastapi import Depends, FastAPI, Query
class Pagination:
def __init__(self, page: Annotated[int, Query(ge=1)] = 1) -> None:
self.page = page
app = FastAPI()
@app.get("/items")
def items(p: Annotated[Pagination, Depends()]) -> dict:
return {"page": p.page}"""Real traps, pinned on FastAPI 0.128.8."""
from typing import Annotated
import pytest
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from app import future_gotcha
def test_class_dependency_with_postponed_annotations_fails_at_request_time():
c = TestClient(future_gotcha.app, raise_server_exceptions=False)
# import and startup succeed; the first request fails (PydanticUserError -> 500)
assert c.get("/items?page=2").status_code == 500
def test_exception_after_yield_cannot_change_a_sent_response():
app = FastAPI()
def commit_in_teardown():
yield "session"
raise RuntimeError("commit failed after the response")
@app.get("/t")
def t(s: Annotated[str, Depends(commit_in_teardown)]) -> dict:
return {"ok": True}
r = TestClient(app, raise_server_exceptions=False).get("/t")
assert (r.status_code, r.json()) == (200, {"ok": True}) # the client saw success
with pytest.raises(RuntimeError): # the failure is only server-side
TestClient(app).get("/t")فایل پروژه نسخههای پشته را ثابت میکند؛ یادداشت نسخه در ابتدای صفحه را ببینید:
[project]
name = "dependency-injection-depends"
version = "0.1.0"
description = "Snippets for the Dependency Injection chapter: Depends, sub-dependencies, caching, yield, router and global dependencies, overrides"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. On 3.12+ you can move to the latest releases.
requires-python = ">=3.9"
dependencies = [
"fastapi==0.128.8",
# Pinned explicitly: the versions every "real run" on the page used.
"starlette==0.49.3",
"pydantic==2.13.5",
"sqlalchemy==2.0.58",
"uvicorn[standard]==0.39.0",
# Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
"eval-type-backport==0.4.0; python_version < '3.10'",
]
[project.optional-dependencies]
test = [
"httpx==0.28.1",
"pytest==8.4.2",
]
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
packages = ["app"]
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]نگاه Python
DI در FastAPI از Python معمولی ساخته شده؛ به همین دلیل مرحلهٔ ثبت جداگانه ندارد. Dependable هر چیزی است که قابل فراخوانی باشد: تابع، کلاس که فراخوانیاش نمونه میسازد، یا نمونهای با __call__. FastAPI پارامترها را با inspect.signature میخواند. «گراف» چیزی جز پارامترهایی نیست که پیشفرض یا فرادادهٔ (Metadata) Annotated آنها شیء Depends است. typing.Annotated در PEP 593 نوع واقعی را برای ویرایشگر و mypy نگه میدارد و نشانگر Depends(...) را کنارش حمل میکند. چون Annotated[...] شیء معمولی است، SessionDep = Annotated[Session, Depends(get_session)] به تعبیر مستندات "just standard Python, it's called a 'type alias'" است. Dependencyهای دارای yield مولد (Generator) هستند. FastAPI آنها را با contextlib.contextmanager یا asynccontextmanager میپوشاند و روی AsyncExitStack وارد میکند؛ بنابراین Teardown همان کد معمولی finally است و آخرین ورودی، اولین خروجی است.
یک لبهٔ تیز از خود Python میآید. FastAPI Annotation رشتهای ناشی از from __future__ import annotations را با __globals__ همان Callable حل میکند. تابع این ویژگی را دارد؛ کلاس و نمونهٔ Callable ندارند. در 0.128.8، Dependency کلاسی در چنین ماژولی هنگام درخواست با PydanticUserError و پاسخ ۵۰۰ شکست میخورد؛ اجرای واقعی در app/future_gotcha.py. نمونهٔ Callable شکل دیگری شکست میخورد: Annotation متد __call__ رشته میماند، پس FastAPI، user را پارامتر Query اجباری میبیند و پاسخ ۴۲۲ با missing و loc: ["query", "user"] میدهد. این هم با افزودن Future import به کپی آزمایشی app/deps.py اجرا و در runs/future-annotations-deps.txt ثبت شد. قطعهکدها روی 3.9 در این ماژول بهجای X | None از Optional[X] استفاده میکنند. عبارت type SessionDep = Annotated[...] در Python 3.12 یک TypeAliasType میسازد، نه مقدار معمولی Annotated. FastAPI 0.128.2 در ۲۰۲۶-۰۲-۰۵، در محدودهٔ نسخهٔ ثابت قطعهکد، "support for PEP695 TypeAliasType" را افزود؛ اما مستندات و قطعهکدها شکل انتساب را به کار میبرند که از 0.95 در همهٔ نسخهها کار میکند.
فهرست مفاهیم
تزریق وابستگی چیست: وارونگی کنترل در یک جمله حیاتی
به زبان ساده: تابع بهجای ساختن یا پیداکردن همکارانش، نام آنها را اعلام میکند؛ Framework آنها را میسازد و تحویل میدهد. کنترل ساخت همکاران از تابع به فراخواننده منتقل میشود؛ این وارونگی کنترل (Inversion of control) است.
بدفهمی رایج: «تزریق وابستگی (Dependency injection) به ظرف (Container)، دفتر ثبت (Registry) یا Decorator روی هر سرویس نیاز دارد.» دادن یک همکار به آرگومان تابع یا سازنده خودش DI است؛ Fowler آن شکل را Constructor Injection مینامد. Container فقط سیمکشی (Wiring) اجزا را خودکار میکند. FastAPI اصلاً Container ندارد؛ امضای تابع نقش ثبت را دارد.
تعریف: مستندات FastAPI: "'Dependency Injection' means, in programming, that there is a way for your code (in this case, your path operation functions) to declare things that it requires to work and use: 'dependencies'. And then, that system (in this case FastAPI) will take care of doing whatever is needed to provide your code with those needed dependencies ('inject' the dependencies)." Fowler سه شکل نام میبرد: "Constructor Injection, Setter Injection, and Interface Injection". در مقابل، در Service Locator، "every user of a service has a dependency to the locator". اصل وارونگی وابستگی قاعدهٔ طراحی پشت آن است: کد سطح بالا به انتزاعهای تحت مالکیت خودش وابسته است و سیمکشی (Wiring) اجزا پیادهسازی واقعی را تعیین میکند.
Without DI (route fetches) With DI (route declares)
1 def list_notes(request): def list_notes(session: SessionDep, user: TenantUser):
2 db = ServiceLocator.get("db") <- asks ... uses session, user
3 user = parse_auth(request.headers) FastAPI, per request:
4 ... uses db, user 4 solve graph: get_engine -> get_session; oauth2_scheme -> get_current_user
5 5 call list_notes(session=..., user=...)
6 test: patch ServiceLocator globals test: app.dependency_overrides[get_current_user] = fakeسناریوی واقعی: Route پرداخت با کاربر جاری، Session و Client ارائهدهندهٔ پرداخت؛ Route عمومی با فقط بررسی محدودیت نرخ (Rate limit)؛ SaaS چندمستأجری که هر Query باید با Tenant آمده از Header فیلتر شود؛ Router مدیریت با API key برای همهٔ Routeها؛ مجموعه تستی که هرگز نباید ارائهدهندهٔ واقعی هویت را صدا بزند.
| اصطلاح | معنا | شکل در FastAPI |
|---|---|---|
| وارونگی کنترل (Inversion of control) | Framework کد را صدا میزند و ورودیاش را تعیین میکند | FastAPI، Path operation و Dependable را فراخوانی میکند |
| تزریق وابستگی (Dependency injection) | همکاران تحویل داده میشوند، جستوجو نمیشوند | پارامترهای Depends(...) |
| مکانیاب سرویس (Service locator) | کد همکاران را از Registry میخواهد | اینجا ضدالگو است؛ ضدالگوها |
| تزریق سازنده (Constructor injection) | همکاران آرگومان __init__ هستند | Dependency کلاسی و سرویس معمولی Python |
| ظرف DI (DI container) | Registry که با بستن (Binding) شیء میسازد | داخلی نیست؛ Laravel و fx دارند |
| ریشهٔ ترکیب (Composition root) | محل واحد ساخت گراف اشیا | امضاها بههمراه create_app() |
راهحل / نحوهٔ استفاده: Route و سرویس همکاران را دریافت کنند. Connection زنده یا Client سراسری را داخل منطق کسبوکار import نکنید؛ شیء بلندعمر را در Lifespan بسازید و با Dependency تحویل دهید.
Depends() و فراهمکنندهٔ آن حیاتی
به زبان ساده: Depends(get_x) به FastAPI میگوید «پیش از این تابع، get_x را صدا بزن و نتیجهاش را اینجا بگذار». get_x درست مثل Route میتواند Query، Header، Cookie، Body، Dependency دیگر، Request، Response و BackgroundTasks اعلام کند.
بدفهمی رایج: «باید Depends(get_x()) نوشت.» مستندات میگویند "You don't call it directly (don't add the parenthesis at the end), you just pass it as a parameter to Depends()." در Depends(get_x()) نتیجهٔ یک فراخوانی در زمان import را میدهید که Callable نیست. بدفهمی دیگر این است که Dependency نوع ویژهای از تابع است؛ در واقع "a path operation function without the 'decorator'" است.
تعریف: امضای مرجع در نسخهٔ ثابت Depends(dependency=None, *, use_cache=True, scope=None) در params.py نسخهٔ 0.128.8 است؛ 0.163.0، max_concurrency را اضافه میکند. آموزش میگوید "Whenever a new request arrives, FastAPI will take care of: Calling your dependency ('dependable') function with the correct parameters. Get the result from your function. Assign that result to the parameter in your path operation function." ورودی درخواست هم اعتبارسنجی (Validation) و مستند میشود: "All the request declarations, validations and requirements of your dependencies (and sub-dependencies) will be integrated in the same OpenAPI schema." تست قطعهکد اطمینانسنجی میکند که page، size، x-tenant-id و x-request-id، با اینکه داخل Dependency اعلام شدهاند، پارامترهای GET /notes در /openapi.json هستند.
def get_tenant(x_tenant_id: Annotated[str, Header(pattern=...)]) -> str
1 GET /notes X-Tenant-ID: acme
2 FastAPI: list_notes needs tenant: TenantDep -> Depends(get_tenant)
3 read header x-tenant-id "acme", validate pattern -> ok
4 call get_tenant(x_tenant_id="acme") -> "acme"
5 list_notes(..., tenant="acme", ...)
6 X-Tenant-ID: Bad_Tenant -> 422 string_pattern_mismatch, loc ["header","x-tenant-id"] (real run)سناریوی واقعی: فیلتر مشترک Query با q، skip و limit؛ Header مربوط به Tenant؛ خواندن Accept-Language؛ Dependency کاربر جاری، بررسی Feature flag، Session پایگاه داده و شیء تنظیمات.
| اعلان Dependable | FastAPI از کجا میخواند | در OpenAPI دیده میشود؟ |
|---|---|---|
page: int = 1 | Query string | بله، در هر Route مصرفکننده |
x_tenant_id: Annotated[str, Header()] | Header به نام x-tenant-id | بله |
session_id: Annotated[str | None, Cookie()] = None | Cookie | بله |
body: SomeModel | Body در JSON، ادغامشده با Body در Route | بله |
request: Request، response: Response | اشیای تزریقشده | نه |
tasks: BackgroundTasks | فهرست Taskهای درخواست | نه |
security_scopes: SecurityScopes | Scopeهای همهٔ Dependantها | نه؛ Scope زیر security میآید |
x: Annotated[X, Depends(f)] | نتیجهٔ f | ورودیهای خود f دیده میشوند |
راهحل / نحوهٔ استفاده: Dependable تابع کوچک و تایپدار باشد؛ بدون فراخوانی پاس داده شود و ورودیهای خودش را با Query() و Header() اعلام کند تا یک بار Validation شوند و همهجا مستند باشند.
Dependency کلاسی حیاتی
به زبان ساده: کلاس قابل فراخوانی (Callable) است و فراخوانیاش نمونه میسازد؛ پس میتواند Dependency باشد. FastAPI پارامترهای __init__ را میخواند، برای هر درخواست نمونه میسازد و تزریق میکند. بهجای دیکشنری، دسترسی به Attribute و تکمیل خودکار ویرایشگر دارید.
بدفهمی رایج: «در Annotated[Pagination, Depends(Pagination)] اولین Pagination فراخوانی میشود.» مستندات دربارهٔ اولی میگویند "doesn't have any special meaning for FastAPI"؛ آرگومان Depends فراخوانی میشود. میانبر Annotated[Pagination, Depends()] یعنی کلاسِ اعلانشده را فراخوانی کن. دام دوم در 0.128.8 واقعی است: با from __future__ import annotations، Annotationهای __init__ رشته میمانند. برنامه شروع میشود اما اولین درخواست با PydanticUserError: TypeAdapter[...ForwardRef(...)] is not fully defined و پاسخ ۵۰۰ شکست میخورد؛ tests/test_gotchas.py.
تعریف: "What FastAPI actually checks is that it is a 'callable' (function, class or anything else) and the parameters defined." آموزش، Depends() بدون آرگومان را "just a shortcut" میداند، برای وقتی که "the dependency is specifically a class that FastAPI will 'call' to create an instance of the class itself".
class Pagination: __init__(self, page: Query(ge=1) = 1, size: Query(ge=1, le=100) = 20)
1 PageDep = Annotated[Pagination, Depends()]
2 GET /notes?page=2&size=2
3 FastAPI: Pagination(page=2, size=2) -> instance; .offset == 2
4 SELECT ... LIMIT 2 OFFSET 2 -> ids [3, 4] (real run)
5 GET /notes?page=0 -> 422 greater_than_equal, loc ["query","page"] (real run)سناریوی واقعی: پارامترهای صفحهبندی (Pagination) و مرتبسازی مشترک میان Endpointهای فهرست؛ شیء فیلتر با status، created_after و q؛ شیء Context درخواست با Locale و منطقهٔ زمانی؛ مدل Pydantic برای Query که در اعتبارسنجی درخواست آمده است.
| شکل | FastAPI چه چیزی را صدا میزند | مقدار تزریقشده | زمان استفاده |
|---|---|---|---|
Depends(common_params) با خروجی dict | تابع | dict | در کد جدید هرگز؛ تکمیل خودکار ندارد |
Annotated[Pagination, Depends(Pagination)] | کلاس | نمونه | شکل صریح |
Annotated[Pagination, Depends()] | کلاسِ Annotation | نمونه | میانبر |
Annotated[Filters, Query()] با مدل Pydantic | Pydantic | مدل | Query پرفیلد و Validatorها |
Annotated[Any, Depends(Pagination)] | کلاس | نمونه | کار میکند ولی اطلاعات نوع از دست میرود |
راهحل / نحوهٔ استفاده: برای گروه پارامترها Dependency کلاسی بسازید. روی 0.128.8 در ماژول تعریف کلاس یا نمونهٔ Callable از from __future__ import annotations استفاده نکنید؛ روی 3.9، Optional[X] بنویسید و روی 3.10+، X | None در زمان اجرا ارزیابی میشود.
نام مستعار Annotated و SessionDep حیاتی
به زبان ساده: Dependency را یک بار با نام مستعار نوع (Type alias) تعریف کنید: SessionDep = Annotated[Session, Depends(get_session)]؛ سپس در هر Route بنویسید session: SessionDep. Alias هم نوع موردنیاز ویرایشگر را حمل میکند، هم دستور FastAPI را.
بدفهمی رایج: «Alias قابلیت خاص FastAPI با قواعد مستقل است.» متغیر معمولی حامل شیء Annotated است. البته نتیجهٔ مهمی دارد: از 0.163.0، شیء Depends با max_concurrency محدودیتش را میان همهٔ Routeهایی که همان Alias را استفاده میکنند شریک میکند: "To share a limit, reuse the same Depends() object, for example in an Annotated alias like this one".
تعریف: آموزش: "because we are using Annotated, we can store that Annotated value in a variable and use it in multiple places" و "the type information will be preserved, which means that your editor will be able to keep providing you with autocompletion, inline errors, etc. The same for other tools like mypy." آموزش SQLModel در مستندات FastAPI دقیقاً SessionDep = Annotated[Session, Depends(get_session)] را تعریف میکند و هدف را میگوید: "We will create a FastAPI dependency with yield that will provide a new Session for each request. This is what ensures that we use a single session per request."
SessionDep = Annotated[Session, Depends(get_session)]
1 def list_notes(session: SessionDep, ...) -> mypy sees Session; FastAPI sees Depends(get_session)
2 def create_note(session: SessionDep, ...) -> same object, same cache key
3 request: get_engine(request) -> engine (app.state)
4 get_session(engine) -> Session(engine), yield
5 list_notes(session=<Session>)
6 teardown: session.close() -> SQL log shows ROLLBACK of the read transaction (real run)SQL ارسالی list_notes از Session تزریقشده با echo=True ثبت شده است؛ اجرای واقعی در runs/sql-echo.txt. Schema ساختهشدهٔ SQLAlchemy هم در همان Log است:
-- GET /notes?page=2&size=2 with X-Tenant-ID: acme (SQLAlchemy 2.0.58, SQLite)
BEGIN (implicit);
SELECT notes.id, notes.tenant_id, notes.title, notes.owner
FROM notes
WHERE notes.tenant_id = ? ORDER BY notes.id
LIMIT ? OFFSET ?; -- parameters ('acme', 2, 2): tenant from get_tenant, size and offset from Pagination
ROLLBACK; -- session.close() in get_session's finally ends the read transaction
-- the DDL create_all() emitted for app/db.py (same log); the composite unique key is what the Before app trips over
CREATE TABLE notes (
id INTEGER NOT NULL,
tenant_id VARCHAR(32) NOT NULL,
title VARCHAR(120) NOT NULL,
owner VARCHAR(50) NOT NULL,
PRIMARY KEY (id),
UNIQUE (tenant_id, title),
FOREIGN KEY(tenant_id) REFERENCES tenants (id)
);
CREATE INDEX ix_notes_tenant_id ON notes (tenant_id);سناریوی واقعی: Aliasهای SessionDep، CurrentUser، AdminUser، TenantDep، SettingsDep و HttpClientDep در app/dependencies.py که همهٔ Routerها import میکنند؛ Type checker نیز استفادهٔ غلط از session.scalar(...) را میگیرد چون نوع Session است، نه Any.
| Alias | بسط آن | عمر مقدار |
|---|---|---|
SessionDep | Annotated[Session, Depends(get_session)] | درخواست |
PageDep | Annotated[Pagination, Depends()] | درخواست |
TenantDep | Annotated[str, Depends(get_tenant)] | درخواست |
CurrentUser | Annotated[User, Security(get_current_user, scopes=["notes:read"])] | درخواست |
WriterUser | Annotated[User, Security(get_current_user, scopes=["notes:write"])] | درخواست، با کلید Cache جدا |
TenantUser | Annotated[User, Depends(get_tenant_user)] | درخواست |
راهحل / نحوهٔ استفاده: برای هر Dependency یک Alias در app/dependencies.py؛ Routeها Alias را import کنند، نه Dependable را. نام بر اساس چیزی باشد که تحویل میدهد، مثل SessionDep، نه چگونگی ساخت آن، مثل GetSessionDep.
زیروابستگیها و گراف وابستگی حیاتی
به زبان ساده: هر Dependency میتواند زیروابستگی (Sub-dependency) داشته باشد. get_tenant_user کاربر جاری و Tenant را میخواهد و کاربر جاری به Bearer token نیاز دارد. FastAPI این لینکها را تا برگها دنبال میکند و از پایین حل میکند. شکل ابتدا درخت است و با اشتراک گرهها، گراف میشود.
بدفهمی رایج: «همهٔ Sub-dependencyها را باید روی Route بنویسم.» Route فقط مصرف خودش را اعلام میکند. مستندات: "Notice that we are only declaring one dependency in the path operation function, the query_or_cookie_extractor. But FastAPI will know that it has to solve query_extractor first, to pass the results of that to query_or_cookie_extractor while calling it."
تعریف: "You can create dependencies that have sub-dependencies. They can be as deep as you need them to be." تابعی که هم Dependency دارد و هم خودش Dependency است، هم "a 'dependable' itself" است و هم "a 'dependant' too". در کد 0.128.8، solve_dependencies روی dependant.dependencies به ترتیب اعلان حلقه میزند. ابتدا Sub-dependencyهای هر گره را بازگشتی حل میکند، بعد مقدار را از Cache میگیرد یا تابع را فراخوانی میکند؛ در پایان پارامترهای Path، Query، Header، Cookie و Body همان گره را میخواند.
POST /notes, graph from the diagram above
1 request_context (global)
2 get_engine -> get_session (SessionDep: yield, setup now)
3 oauth2_scheme -> get_current_user[notes:write] (WriterUser)
4 oauth2_scheme[notes:read] -> get_current_user[notes:read] -> get_tenant -> get_tenant_user (TenantUser)
5 body NoteIn validated, Request, BackgroundTasks injected
6 create_note(...) runs; oauth2_scheme and get_current_user each ran twice (real run: 2 + 2 calls; a security
scheme's cache key includes the scopes it is solved under, so the notes:write and notes:read branches do not share it)سناریوی واقعی: زنجیرهٔ get_current_active_user روی get_current_user روی oauth2_scheme؛ Repository آگاه از Tenant روی Session و Tenant؛ بررسی Permission روی کاربر و منبع بارگذاریشده با شناسه.
| ویژگی گراف | رفتار در 0.128.8، از اجرا یا کد |
|---|---|
| عمق | نامحدود |
| گره مشترک | یک بار در درخواست حل و مقدار از Cache بازاستفاده میشود |
Callable یکسان با Scopeهای متفاوت Security | کلید جدا؛ یک فراخوانی برای هر مجموعهٔ Scope، شامل Scheme زیر آن؛ oauth2_scheme در POST /notes دو بار اجرا شد |
| خطای Validation در چند گره | همه جمع میشوند؛ یک پاسخ 422 با همهٔ مدخلهای detail |
HTTPException در گره | حل متوقف میشود؛ گرههای بعد و Route اجرا نمیشوند |
| چرخه | Python بدون Forward reference نمیتواند چرخه بیان کند؛ نسازید |
راهحل / نحوهٔ استفاده: Dependable کوچک بسازید و ترکیب کنید. وظیفهٔ هرکدام یکی باشد: خواندن Token، بارگذاری کاربر، بررسی Tenant. Route فقط گره بالایی را نام ببرد.
ترتیب حل Dependencyها مهم
به زبان ساده: ابتدا Dependency سراسری برنامه، سپس Router، بعد Decorator، بعد پارامترها به ترتیب امضا و در پایان تابع شما اجرا میشوند.
بدفهمی رایج: «ترتیب پارامترها برای Dependency مهم نیست.» برای منشأ مقدار مهم نیست؛ اما ترتیب اثر جانبی (Side effect) را تعیین میکند. Rate limiter بعد از Dependency مربوط به Session، حتی برای درخواستی که رد میکند Session باز کرده است.
تعریف: آموزش برنامههای بزرگتر میگوید "The router dependencies are executed first, then the dependencies in the decorator, and then the normal parameter dependencies." کاوشگر قطعهکد ترتیب کامل، شامل سطح برنامه را تأیید میکند؛ اجرای واقعی در test_resolution_order_app_router_decorator_parameter.
GET /order on app/lifecycle.py (real run)
1 app dependency
2 router dependency
3 decorator dependency
4 parameter dependency
5 route
6 response.start 200سناریوی واقعی: بررسی API key در Router پیش از بازکردن Session؛ Dependency شناسهٔ درخواست پیش از هر Log؛ بررسی Tenant پیش از هر Query فیلترشده با Tenant.
| سطح | محل اعلان | زمان اجرا | مقدار دریافت میشود؟ |
|---|---|---|---|
| 1 | FastAPI(dependencies=[...]) | اول | نه |
| 2 | APIRouter(dependencies=[...]) / include_router(..., dependencies=[...]) | دوم | نه |
| 3 | @router.get(..., dependencies=[...]) | سوم | نه |
| 4 | پارامترهای تابع، از چپ به راست | چهارم | بله |
| 5 | داخل هر گره، ابتدا Sub-dependencyها | عمقاول | بله، به والد |
راهحل / نحوهٔ استفاده: بررسی ارزانِ ردکننده مثل API key و Feature flag را در Router یا Decorator بگذارید؛ منبع گران مثل Session و Client را انتهای امضا بیاورید.
Cache و use_cache: یک مقدار در هر درخواست حیاتی
به زبان ساده: اگر چند بخش گراف همان Dependency را بخواهند، FastAPI در هر درخواست یک بار آن را فراخوانی میکند و همان مقدار را به همه میدهد. درخواست تازه، فراخوانی تازه دارد.
بدفهمی رایج: «Cache میان درخواستها مشترک است.» دیکشنری برای هر درخواست ساخته میشود: dependency_cache = {} در solve_dependencies. بدفهمی دوم: «تابع یکسان همیشه یک مدخل دارد.» کلید 0.128.8 برابر (call, scopes_for_cache, computed_scope) است. پس Security(get_current_user, scopes=["notes:write"]) و Security(get_current_user, scopes=["notes:read"]) در همان درخواست دو مدخل و دو اجرا دارند. اندازهگیری قطعهکد: POST /notes دو بار و DELETE /notes/{id} یک بار جستوجوی Token را فراخوانی کرد.
تعریف: آموزش: "If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request." برای خروج از این رفتار: "you can set the parameter use_cache=False when using Depends". مرجع میافزاید "the dependency is called again (if declared more than once) in the same request."
GET /cache (left and right both need counted) GET /nocache
1 counted() -> 1, stored under key(counted) counted() -> 1
2 left(n=1) Depends(counted, use_cache=False) -> counted() -> 2
3 right(n=1) (cache hit) {"a": 1, "b": 2, "calls": 2} (real run)
4 {"left": 1, "right": 1, "calls": 1} (real run)
5 next request: cache is new -> calls 2سناریوی واقعی: کاربر جاری فقط یک بار بارگذاری شود، با اینکه Route و Permission check و Dependency ثبت Audit همگی آن را میخواهند؛ Session مشترک میان Repository و Route؛ زمان «اکنون» یکسان برای همهٔ بخشهای درخواست با Cache، در برابر UUID تازه برای هر مصرف با use_cache=False.
| وضعیت | تعداد فراخوانی در درخواست |
|---|---|
سه Dependant از همان Depends(f) استفاده کنند | 1 |
ابتدا Depends(f) و سپس Depends(f, use_cache=False) | 2، اجرای واقعی |
ابتدا Depends(f, use_cache=False) و سپس Depends(f) | 1؛ فراخوانی بدون Cache هم نتیجه را ذخیره میکند و اعلان بعدی آن را میگیرد؛ اجرای واقعی /nocache-first |
Security(f, scopes=["a"]) و Security(f, scopes=["b"]) | 2؛ Scope در کلید است |
دو بار Security(f, scopes=["a"]) | 1 |
Depends(f) و Depends(f, scope="function") | 2؛ حوزه در کلید است؛ اجرای واقعی runs/probe6-output.txt |
| دو درخواست متفاوت | هرکدام 1 |
f جایگزینشده | 1؛ Override زیر کلید اصلی Cache میشود |
قاعدهٔ دقیق حلقه در 0.128.8: اعلان با use_cache=False هرگز Cache را نمیخواند، اما بعد از هر فراخوانی اگر کلید هنوز مقداری نداشته باشد نتیجه ذخیره میشود. پس این گزینه فقط اجرای تازهٔ همان اعلان را تضمین میکند؛ اعلان Cacheدار بعدی همان Callable، نتیجهٔ اولین اجرا را میگیرد، خواه Cacheدار بوده باشد یا نه؛ tests/test_lifecycle.py::test_uncached_declaration_first_feeds_the_cache.
راهحل / نحوهٔ استفاده: برای جستوجوی گران کاربر، Tenant و تنظیمات به Cache تکیه کنید، اما بدانید Scopeها آن را جدا میکنند. use_cache=False فقط برای مقدار الزاماً تازه در هر مصرف است؛ اگر اعلانهای Cacheدار نباید مقدارش را ببینند، آن را بعد از آنها بگذارید.
Dependency مولد با yield: آمادهسازی و Teardown حیاتی
به زبان ساده: Dependency که بهجای return از yield استفاده میکند دو نیمه دارد: کد پیش از yield پیش از Route اجرا میشود، مقدار تزریق میشود و کد پس از آن هنگام پایان درخواست اجرا میشود. پاکسازی را در finally بگذارید تا روی خطا هم اجرا شود.
بدفهمی رایج: «باید @contextmanager روی آن بگذارم.» مستندات: "you don't have to use the decorators for FastAPI dependencies (and you shouldn't). FastAPI will do it for you internally." دیگری: «برای دو مقدار، دو بار yield میکنم.» مستندات: "Make sure to use yield one single time per dependency."
تعریف: "FastAPI supports dependencies that do some extra steps after finishing. To do this, use yield instead of return, and write the extra steps (code) after." همچنین "Any function that is valid to use with: @contextlib.contextmanager or @contextlib.asynccontextmanager would be valid to use as a FastAPI dependency." دربارهٔ خطا: "If you use a try block in a dependency with yield, you'll receive any exception that was thrown when using the dependency... you can use finally to make sure the exit steps are executed, no matter if there was an exception or not." درخت هم ترتیب درست دارد: "FastAPI will make sure that the 'exit code' in each dependency with yield is run in the correct order." این ترتیب معکوس Setup است، چون هر Dependency هنگام خروج "needs the value from" زیروابستگیاش "to still be available".
GET /teardown: dep_c -> dep_b -> dep_a, all yield (real run, 0.128.8)
1 a setup
2 b setup
3 c setup
4 route (adds a background task)
5 response.start 200
6 background task ran
7 c teardown -> b teardown -> a teardownسناریوی واقعی: بستن Session در finally؛ آزادکردن قفل (Lock)؛ حذف پوشهٔ موقت؛ پایاندادن Span ردیابی؛ Client از httpx برای هر درخواست در طراحی قدیمی، هرچند یک Client در Lifespan بهتر است؛ پوشاندن منبع async with با Dependency مولد async.
| بخش Generator | زمان اجرا | چه میبیند |
|---|---|---|
پیش از yield | پیش از Route، به ترتیب گراف | پارامترها و Sub-dependencyهای خودش |
yield value | مقدار تزریق میشود | — |
except SomeError | اگر Route یا Dependency بعدی، SomeError پرتاب کند | استثنا |
پس از yield، بدون استثنا | پیشفرض پس از پاسخ | مقدارهای Sub-dependency هنوز زندهاند |
finally | همیشه | — |
دومین yield | هرگز معتبر نیست | RuntimeError از contextlib |
راهحل / نحوهٔ استفاده: شکل try/yield/except: rollback; raise/finally: close در get_session را دنبال کنید. هر Dependency یک منبع؛ اگر پاکسازی await دارد، Generator async باشد.
استثنا در Dependency: HTTPException، except و پرتاب دوباره حیاتی
به زبان ساده: Dependency با پرتاب HTTPException پیش از Route درخواست را متوقف میکند؛ Authentication همینطور کار میکند. Dependency مولد با yield استثناهای بعد از نقطهٔ yield، در Route یا Dependencyهای بعدی، را هم میبیند و میتواند تبدیل کند؛ اما باید دوباره پرتاب کند یا استثنای تازهای بدهد.
بدفهمی رایج: «اگر استثنا را بگیرم، Client پاسخ خوب من را میگیرد.» دربارهٔ گرفتن بدون پرتاب، مستندات میگویند "FastAPI won't be able to notice there was an exception" و "the client will see an HTTP 500 Internal Server Error response as it should... but the server will not have any logs or any other indication of what was the error". اجرای GET /swallow پاسخ ۵۰۰ را نشان میدهد. ValueError اصلی گم میشود، ولی 0.128.8 کاملاً ساکت نیست: با پیشفرض raise_server_exceptions=True در TestClient، درخواست این خطا را پرتاب میکند: FastAPIError: Response not awaited. There's a high chance that the application code is raising an exception and a dependency with yield has a block with a bare except, or a block with except Exception, and is not raising the exception again. منشأ آن بررسی response_awaited در routing.py است؛ Dependency بلعنده را نشان میدهد، نه علت اصلی را. رفتار در 0.110.0 عوض شد؛ پیش از آن استثنای بلعیدهشده "would be automatically raised/forwarded to any exception handlers".
تعریف: "If you catch an exception in a dependency with yield, unless you are raising another HTTPException or similar, you should re-raise the original exception." تبدیل مجاز است: get_username در آموزش، OwnerError را بعد از yield میگیرد و HTTPException(status_code=400, ...) میدهد. Client پاسخ ۴۰۰ میگیرد؛ خروجی واقعی {"detail": "Owner error: rick"}. این کار میکند چون استثنای Route پیش از ساخت پاسخ به Generator پرتاب میشود.
/denied: raise HTTPException(403) before yield/return /translate: route raises OwnerError
1 dependency raises 403 translating() yielded "rick"
2 route NOT called ("route must not run" absent) route raises OwnerError
3 403 {"detail": "denied in dependency"} exception thrown into generator at yield
4 except OwnerError -> raise HTTPException(400)
5 400 {"detail": "Owner error: rick"} (real run)سناریوی واقعی: پاسخ ۴۰۱ و ۴۰۳ از Authentication؛ پاسخ ۴۰۴ از Dependency «منبع را با شناسه بخوان یا شکست بخور»؛ تبدیل IntegrityError به ۴۰۹ در Dependency پایگاه داده، هرچند Route یا Handler جای بهتری است؛ Session که Rollback میکند و دوباره پرتاب میکند.
| محل و شکل استثنا | نتیجه برای Client |
|---|---|
HTTPException پیش از yield/return | همان وضعیت؛ Route اجرا نمیشود |
استثنای Route با except ...: raise در Dependency | رسیدگی معمول، Handler یا 500؛ پاکسازی انجام شده |
تبدیل استثنای Route به HTTPException در except | وضعیت تبدیلشده، 400 در کاوشگر |
| گرفتن استثنای Route بدون پرتاب دوباره | 500؛ علت اصلی گم میشود، سرور فقط FastAPIError: Response not awaited میبیند؛ اجرای واقعی 0.128.8 |
پرتاب پس از yield در روند موفقیت | Client قبلاً 200 گرفته؛ خطا فقط در سرور نمایان است؛ TestClient واقعاً RuntimeError را دوباره پرتاب کرد |
| خطای Validation پارامتر Dependency | 422؛ Route اجرا نمیشود |
راهحل / نحوهٔ استفاده: برای «اجازهٔ ادامه نداری»، HTTPException بدهید. در Dependency مولد با yield بنویسید except: rollback(); raise. استثنای دامنه (Domain) را در Exception handler نگاشت کنید؛ استثناها و پاسخها.
زمان Teardown: ابتدا پاسخ، سپس Background task و scope="function" حیاتی
به زبان ساده: در FastAPI جاری، پاسخ پیش از Teardown ارسال میشود؛ کد بعد از yield وقتی اجرا میشود که Client پاسخ را گرفته است. اگر زودتر لازم است، مثلاً آزادکردن Connection پیش از پاسخ Streaming طولانی، scope="function" اعلام کنید.
بدفهمی رایج: «بعد از yield، Commit طبیعیِ پایان درخواست است.» در Scope پیشفرض، Commit پس از ارسال پاسخ است و شکستش دیگر ۲۰۰ را به خطا تبدیل نمیکند. بنابراین get_session در قطعهکد فقط Rollback و Close میکند؛ create_note در Route، Commit میکند و IntegrityError را به ۴۰۹ تبدیل میکند؛ اجرای واقعی. بدفهمی دوم: «هنگام اجرای Background task، Session تحویلشده بسته شده است.» در 0.128.8 ترتیب واقعی شروع پاسخ → Task → Teardown بود؛ با این حال مستندات منابع مستقل برای Task میخواهند و رفتار میان نسخهها تغییر کرده است.
تعریف: "Normally the exit code of dependencies with yield is executed after the response is sent to the client. But if you know that you won't need to use the dependency after returning from the path operation function, you can use Depends(scope="function")". دو مقدار: "'function': start the dependency before the path operation function that handles the request, end the dependency after the path operation function ends, but before the response is sent back to the client" و "'request': ... but end after the response is sent back to the client". پیشفرض: "If not specified and the dependency has yield, it will have a scope of 'request' by default." محدودیت: "When you declare a dependency with a scope='request' (the default), any sub-dependency needs to also have a scope of 'request'." تاریخچه در جدول یکدقیقهای است. راهنمای پیشرفته دربارهٔ تغییر 0.106.0 میگوید "you should create the resources for background tasks inside the background task itself... instead of passing the object from the database as a parameter to the background task function, you would pass the ID of that object".
GET /function-scope: Depends(early, scope="function") (real run)
1 app dependency
2 function-scope setup
3 route
4 function-scope teardown <- before the response
5 response.start 200ترتیب اجرا، رابطهٔ Task و Dependency مولد با yield را تعیین میکند: در اجرای نسخهٔ ثابت، Task بعد از پاسخ و پیش از Teardown بود، پس Session از نظر فنی هنوز باز بود. دلیل در routing.py نسخهٔ 0.128.8 است: Exit stack درخواست، await response(scope, receive, send) را احاطه میکند و Starlette کارهای پسزمینهٔ پاسخ را داخل همان فراخوانی اجرا میکند. مستندات این ترتیب را تضمین نمیکنند و راهنمای پیشرفته منابع مستقل برای Task را توصیه میکند.
سناریوی واقعی: StreamingResponse که ردیفها را از Session میخواند به Scope پیشفرض درخواست نیاز دارد؛ دانلود Streaming کند که Session را فقط برای Authorization لازم داشته، با scope="function" Connection را زود آزاد میکند؛ Task ثبت Audit که note.id و شناسهٔ درخواست میگیرد، نه Session؛ مثل write_audit در قطعهکد.
| نیاز | انتخاب |
|---|---|
| بستن Session در هر شرایط | finally: session.close() در هر Scope |
| نتیجهٔ Commit باید وضعیت پاسخ را تعیین کند | Commit در Route یا سرویس فراخوانیشدهٔ آن |
| مصرف منبع هنگام Streaming پاسخ | پیشفرض scope="request" |
| منبع فقط برای Authorization و پاسخ کند | scope="function" |
| Task به داده نیاز دارد | شناسه و مقدار ساده؛ Session مستقل |
| پاکسازی نباید دو بار اجرا شود | یک Dependency مولد برای هر منبع، با Cache درخواست |
راهحل / نحوهٔ استفاده: Commit در Route، Close در Dependency، scope="function" برای آزادسازی زودهنگام و شناسهها برای Background task.
Dependency Decorator عملیات مسیر (Path operation decorator) مهم
به زبان ساده: اگر Dependency فقط برای اثر جانبی (Side effect)، مثل بررسی نقش یا کلید است و Route مقدار برگشتیاش را نمیخواهد، آن را در dependencies=[...] روی Decorator بنویسید؛ پارامتر بیمصرف اضافه نکنید.
بدفهمی رایج: «Dependency Decorator نمیتواند مقدار برگرداند یا Sub-dependency داشته باشد.» هر دو مجازند؛ فقط مقدار دور ریخته میشود. مستندات: "they can return values or not, the values won't be used. So, you can reuse a normal dependency (that returns a value) you already use somewhere else". require_admin در قطعهکد کاربر را برمیگرداند و در Decorator استفاده شده است.
تعریف: "The path operation decorator receives an optional argument dependencies... These dependencies will be executed/solved the same way as normal dependencies. But their value (if they return any) won't be passed to your path operation function." دلیل: "Some editors check for unused function parameters, and show them as errors."
@notes.delete("/{note_id}", status_code=204, dependencies=[Depends(require_admin)])
1 DELETE /notes/1 Bearer bob-token -> require_admin: "admin" not in roles -> 403 (real run)
2 DELETE /notes/1 Bearer alice-token -> require_admin returns user (discarded)
3 -> delete_note(note_id=1, session, user) -> 204 (real run)
4 the user is solved once: require_admin and TenantUser share the cache entry (1 call, real run)سناریوی واقعی: بررسی نقش، Feature flag، Rate limit، وجود کلید Idempotency، حالت (Mode) تعمیرات و ثبت Audit دسترسی به Route حساس.
| نیاز | محل |
|---|---|
| مقدار داخل Route | پارامتر |
| فقط بررسی | dependencies=[...] در Decorator |
| بررسی در چند Route | dependencies=[...] در Router |
| بررسی در همهٔ Routeها | FastAPI(dependencies=[...]) |
| مقدار و بررسی | پارامتر؛ بررسی استثنا پرتاب میکند |
راهحل / نحوهٔ استفاده: Guard در Decorator، داده در پارامتر. Guard ارزان باشد چون پیش از Dependency پارامترها اجرا میشود.
Dependencyهای Router و سراسری: APIRouter(dependencies=...) و FastAPI(dependencies=...) حیاتی
به زبان ساده: فهرست APIRouter(dependencies=[...]) برای هر Route همان Router اجرا میشود؛ روی برنامهٔ FastAPI برای هر Route برنامه. مقدار برگشتی مثل Dependency Decorator دور ریخته میشود.
بدفهمی رایج: «Dependency سراسری برای هر درخواست اجرا میشود؛ پس Middleware است.» فقط وقتی Route مطابق پیدا شود اجرا میشود. در اجرای واقعی GET /nope با ۴۰۴، Header به نام X-Request-ID ندارد چون request_context اصلاً اجرا نشد. همچنین پاسخ ساختهشده از HTTPException را تغییر نمیدهد: ۴۰۱ در /whoami، Header تنظیمشدهٔ request_context روی Response تزریقی را از دست داد. برای «هر درخواست، هر پاسخ» از میانافزار (Middleware) استفاده کنید.
تعریف: دربارهٔ سراسری: "Similar to the way you can add dependencies to the path operation decorators, you can add them to the FastAPI application. In that case, they will be applied to all the path operations in the application". دربارهٔ Router: "we can add a list of dependencies that will be added to all the path operations in the router and will be executed/solved for each request made to them" و "Having dependencies in the APIRouter can be used, for example, to require authentication for a whole group of path operations." همان dependencies= در app.include_router(...) نیز پذیرفته میشود. یادداشت 0.137.0، بعد از نسخهٔ ثابت قطعهکد، نگهداری Routerها بهصورت درخت را شرح میدهد و "Dependencies per router" را زیر "Future Features Enabled" میآورد. یک "Non Objective" هم ثبت شده: اجرای Dependency برای ۴۰۴ کنار گذاشته شد چون "Executing dependencies in the router that did not find a match would not make sense".
admin = APIRouter(prefix="/admin", dependencies=[Depends(verify_api_key)])
1 GET /admin/stats (no header) -> 422 missing header x-api-key (real run)
2 GET /admin/stats X-API-Key: x -> 403 "Bad API key"
3 GET /admin/stats X-API-Key: admin-key -> 200 {"acme": 5, "globex": 1}
4 /openapi.json: x-api-key is a parameter of /admin/stats and /admin/audit (test_openapi)
5 GET /nope -> 404 from the router, no global dependency ran, no X-Request-IDسناریوی واقعی: Routerهای /admin پشت API key یا نقش مدیر؛ /internal با بررسی Header منتقلشده از mTLS؛ حلکنندهٔ سراسری Tenant در SaaS چندمستأجری؛ بررسی سراسری پشتیبانی نسخهٔ API؛ یک Router برای هر شریک با Authentication مستقل.
| نیاز | Dependency Router یا سراسری | Middleware |
|---|---|---|
| اجرا برای Path نامنطبق، 404/405 | نه | بله |
| خواندن Header تایپدار و معتبر | بله، همراه مستندسازی | فقط Header خام |
| حضور در OpenAPI | بله | نه |
| جایگزینی در تست | بله | نه؛ باید حذف یا پیکربندی شود |
| مشاهده و ویرایش هر پاسخ | نه؛ روی HTTPException از دست میرود | بله |
| ترتیب نسبت به بقیه | برنامه → Router → Decorator → پارامتر | دور همه قرار میگیرد |
راهحل / نحوهٔ استفاده: Authentication و Tenant در Dependency Router یا برنامه تا مستند و قابل Override باشند؛ شناسهٔ درخواست، زمانسنجی و Header امنیتی در Middleware.
Dependency پارامتردار: کلاس Callable و کارخانهٔ Closure مهم
به زبان ساده: گاهی یک بررسی تنظیم متفاوت میخواهد: «نقش admin لازم است» یا «نقش editor لازم است». کلاسی بسازید که __init__ تنظیم را بگیرد و __call__ همان Dependency باشد؛ یک نمونه را به Depends(...) بدهید. تابعی که تابع Dependency تازه برمیگرداند، یعنی Closure، همین کار را میکند.
بدفهمی رایج: «FastAPI برای نمونهٔ Callable، __init__ را میخواند.» مستندات: "FastAPI won't ever touch or care about init, we will use it directly in our code"؛ تحلیل روی __call__ است. دام تست: app.dependency_overrides[RoleChecker] = ... اثری ندارد؛ کلید باید همان نمونهٔ استفادهشده در Route باشد. نمونه در متغیر ماژول نگه داشته شده: require_admin = RoleChecker("admin"). اجرای واقعی با کلید کلاس ۴۰۳ و با نمونه ۲۰۴ داد.
تعریف: "In Python there's a way to make an instance of a class a 'callable'. Not the class itself (which is already a callable), but an instance of that class. To do that, we declare a method call". همچنین "In this case, this call is what FastAPI will use to check for additional parameters and sub-dependencies" و "In the chapters about security, there are utility functions that are implemented in this same way." شیء OAuth2PasswordBearer(tokenUrl=...) از همین جنس است.
require_admin = RoleChecker("admin") requires_feature("beta") -> check (a closure)
1 import time: __init__(role="admin") runs once import time: factory runs once per decorator
2 request: FastAPI calls require_admin(user=...) request: check(request) reads app.state.features
3 "admin" not in user.roles -> 403 features["beta"] is False -> 404 (real run)
4 override key: require_admin (the instance) override key: the returned function objectسناریوی واقعی: RoleChecker("admin")، ScopeChecker("billing:write")، RateLimit(times=10, seconds=60)، requires_feature("beta") و ValidatedResource(model=Order) که با شناسه بارگذاری میکند یا ۴۰۴ میدهد؛ کلاسهای امنیتی OAuth2PasswordBearer، APIKeyHeader و HTTPBearer.
| شکل | محل پارامترها | کلید Override | نکته |
|---|---|---|---|
| نمونهٔ کلاس Callable | Attributeهای تنظیمشده در __init__ | همان نمونه | در متغیر ماژول نگه دارید |
| کارخانهٔ Closure (Closure factory) | متغیرهای بستهشده در Closure | تابع برگشتی | هر فراخوانی تابع تازه میسازد؛ Factory را یک بار صدا بزنید و نتیجه را نگه دارید |
functools.partial(fn, role="admin") | آرگومانهای مقید | شیء Partial | پشتیبانی میشود؛ 0.123.x ترکیب partial و wraps را اصلاح کرد |
Security(fn, scopes=[...]) | Scopeهای اعلانشده | fn | جمعشده در SecurityScopes |
| تابع جدا برای هر گونه | ثابت داخل کد | تابع | برای دو گونه خوب است، نه ده گونه |
راهحل / نحوهٔ استفاده: کلاس Callable برای بررسی قابل تنظیم؛ ساخت نمونه فقط یک بار در سطح ماژول؛ Override با همان نمونه. در چند جا داخل Depends(RoleChecker("admin")) نمونهٔ بینام نسازید؛ هرکدام کلید و مدخل Cache جدا دارد.
Dependencyهای async و sync: Event loop و Thread pool مهم
به زبان ساده: قاعده همان Routeهاست. Dependency با async def روی حلقهٔ رویداد (Event loop) اجرا میشود؛ باید await کند و هرگز مسدودکننده (Blocking) نباشد. def معمولی در مجموعهٔ Threadها (Thread pool) اجرا میشود، پس Driver پایگاه دادهٔ sync و I/O فایل آنجا امناند. ترکیب هر دو آزاد است.
بدفهمی رایج: «داخل Route async def، Dependency def هم روی Loop اجرا میشود.» نه؛ در اجرای واقعی، Dependency sync روی AnyIO worker thread و Dependency async روی همان Thread مربوط به Loop و Route اجرا شد. Dependencyهای sync از همان Thread pool با ۴۰ Token مشترک با Routeهای def استفاده میکنند. Setup و Teardown در Generator هم از آن میگذرند؛ contextmanager_in_threadpool در کد 0.128.8.
تعریف: "The same applies for dependencies. If a dependency is a standard def function instead of async def, it is run in the external threadpool." همچنین "You can have multiple dependencies and sub-dependencies requiring each other... some of them might be created with async def and some with normal def. It would still work". Starlette: "The default thread pool size is only 40 tokens... This limit is shared with other libraries: for example FastAPI also uses anyio to run sync dependencies".
async def threads(s = Depends(sync_dep), a = Depends(async_dep)) (real run)
1 sync_dep -> run_in_threadpool -> "AnyIO worker thread"
2 async_dep -> awaited on the loop -> event loop thread
3 route -> same event loop thread as async_dep
4 def get_session (generator) -> contextmanager_in_threadpool: setup and teardown in worker threadsسناریوی واقعی: get_session def با Engine همگام SQLAlchemy؛ async def get_async_session با AsyncSession و Driver ناهمگام؛ Dependency async def که درخواست httpx.AsyncClient به ارائهدهندهٔ هویت را await میکند؛ Dependency def که فایل تنظیمات را یک بار میخواند، هرچند Cache در Lifespan بهتر است.
| کار Dependency | شکل تابع | دلیل |
|---|---|---|
| فقط await روی I/O ناهمگام | async def | جابهجایی Thread ندارد |
| فراخوانی کتابخانهٔ Blocking | def، Thread pool برای sync | Loop آزاد میماند |
| محاسبهٔ خالص در حد میکروثانیه | async def | پرهیز از جابهجایی Thread در هر درخواست |
فراخوانی Blocking داخل async def | هرگز | همهٔ درخواستهای Worker را متوقف میکند |
| Session همگام در برنامهٔ پرهمزمانی | def و اندازهٔ Pool ≥ Threadهای مشغول | 40 Token مشترک با Routeها |
راهحل / نحوهٔ استفاده: نوع Dependency با کتابخانهٔ مصرفی هماهنگ باشد؛ Pool پایگاه داده را متناسب با Thread pool اندازهگذاری کنید. در برنامهٔ async، Session ناهمگام سرتاسری بهتر است؛ جزئیات در SQLAlchemy 2 و SQLModel و سازوکار Thread pool در Async Python.
تزریق Request و Response و request.state مهم
به زبان ساده: هر Dependency میتواند Request خام را برای Header، نشانی Client، request.app و request.state بخواهد؛ همچنین شیء Response که FastAPI، Header و Cookie و کد وضعیتش را روی پاسخ واقعی کپی میکند.
بدفهمی رایج: «Header تنظیمشده روی Response تزریقی همیشه ارسال میشود.» فقط هنگام بازگشت عادی Route. با HTTPException، Exception handler پاسخ جدید میسازد و Response تزریقی کنار میرود؛ در اجرای واقعی ۴۰۱ فاقد X-Request-ID بود. بدفهمی دیگر: «دادهٔ خواندهشده از Request اعتبارسنجی میشود.» مستندات: "if you get data from the Request object directly (for example, read the body) it won't be validated, converted or documented".
تعریف: "By declaring a path operation function parameter with the type being the Request FastAPI will know to pass the Request in that parameter." Starlette دربارهٔ ذخیرهٔ هر درخواست: "If you want to store additional information on the request you can do so using request.state" و دربارهٔ برنامه: "You can store arbitrary extra state on the application instance, using the generic app.state attribute". پارامتر Response در Dependency هم کار میکند؛ صفحههای «Response - Change Status Code» و «Response Headers» راهنمای پیشرفته.
request_context(request: Request, response: Response, x_request_id: Header() = None)
1 rid = x_request_id or uuid4().hex
2 request.state.request_id = rid -> /whoami reads it back (real run)
3 response.headers["X-Request-ID"] = rid -> copied onto the 200 response
4 route raises HTTPException(401) -> new response, header lost (real run)سناریوی واقعی: IP کلاینت برای Audit با request.client.host، انتقال شناسهٔ درخواست، Engine با request.app.state.engine، تنظیم Cookie تازهشده از Dependency مربوط به Authentication، تنظیم Cache-Control از Dependency مربوط به Cache.
| شیء | عمر | مناسب برای | نامناسب برای |
|---|---|---|---|
request.app.state | Process، بهازای Worker | Engine، Client، تنظیمات و Feature flag | دادهٔ هر درخواست و شمارندهٔ مشترک Workerها |
request.state | درخواست | شناسه، زمانسنجی و Tenant حلشده | دادهای که باید پس از درخواست بماند |
Lifespan state با yield {...} | Process؛ کپی سطحی در هر request.state | Client مشترک با نوع TypedDict | دادهٔ تغییرپذیری که انتظار دارید مستقل برای هر درخواست باشد |
Response تزریقی | درخواست، فقط روند موفقیت | Header و Cookie روی بازگشت عادی | Header اجباری روی خطا |
Body خام Request | درخواست | بررسی امضای Webhook | ورودی معمولی؛ آن را اعلام کنید |
راهحل / نحوهٔ استفاده: منبع را داخل Dependency از request.app.state بخوانید، نه با import. دادهٔ هر درخواست روی request.state و Header همیشهحاضر در Middleware باشد.
Dependency امنیتی و Scopeها: OAuth2PasswordBearer، Security() و SecurityScopes حیاتی
به زبان ساده: ابزار امنیتی FastAPI همان Dependency است. OAuth2PasswordBearer(tokenUrl="token") یک Callable است که Authorization: Bearer ... را میخواند و رشتهٔ Token یا پاسخ ۴۰۱ میدهد. get_current_user به آن وابسته است و Token را به کاربر تبدیل میکند. Security() همان Depends() بهعلاوهٔ حوزههای OAuth2 (Scopes) در OpenAPI است.
بدفهمی رایج: «OAuth2PasswordBearer اعتبار Token را بررسی میکند.» فقط استخراج میکند. بررسی امضای JWT، انقضا و ابطال کار get_current_user شماست؛ احراز هویت FastAPI. نکتهٔ نسخه: نبود Header از 0.20.0 در OAuth2PasswordBearer پاسخ ۴۰۱ میدهد؛ تغییر ۴۰۳ به ۴۰۱ در 0.122.0 برای ابزارهای دیگر مثل HTTPBearer و کلاسهای API key است. اجرای نسخهٔ ثابت 401 {"detail":"Not authenticated"} با WWW-Authenticate: Bearer داد.
تعریف: "The oauth2_scheme variable is an instance of OAuth2PasswordBearer, but it is also a 'callable'." و "It will go and look in the request for that Authorization header, check if the value is Bearer plus some token, and will return the token as a str. If it doesn't see an Authorization header, or the value doesn't have a Bearer token, it will respond with a 401 status code error (UNAUTHORIZED) directly." مرجع: Security(dependency=None, *, scopes=None, use_cache=True)؛ "The only difference with a regular dependency is that it can declare OAuth2 scopes that will be integrated with OpenAPI". همچنین "Because the SecurityScopes will have all the scopes declared by dependants, you can use it to verify that a token has the required scopes in a central dependency function". جزئیات مجوز (Authorization)، نقشها، Scopeها و Router مدیریت، موضوع فصل Authorization این بخش است؛ اینجا فقط شکل Dependency را میبینیم.
POST /notes Bearer bob-token (scopes: notes:read) (real run)
1 oauth2_scheme -> "bob-token"
2 get_current_user(security_scopes=["notes:write"]) -> user bob
3 "notes:write" not in bob.scopes -> 403, WWW-Authenticate: Bearer scope="notes:write"
4 /openapi.json: POST /notes security [{"OAuth2PasswordBearer": ["notes:write", "notes:read"]}]
5 GET /notes security [{"OAuth2PasswordBearer": ["notes:read"]}]سناریوی واقعی: ورود کاربر با Bearer token؛ Client ماشینی با API key و APIKeyHeader؛ Scope هر Route برای برنامهٔ شخص ثالث؛ Endpointهای WebSocket با همان Dependency امنیتی، پشتیبانیشده از 0.144.0 و بعد از نسخهٔ ثابت قطعهکد.
| ابزار | چه میخواند | نبود اطلاعات هویت | OpenAPI |
|---|---|---|---|
OAuth2PasswordBearer(tokenUrl=...) | Authorization: Bearer | 401 Not authenticated از 0.20.0؛ اجرای واقعی | جریان password در oauth2 و Scopeها |
HTTPBearer() | Authorization: Bearer | 401 از 0.122.0؛ قبلاً 403 | http bearer |
APIKeyHeader(name="X-API-Key") | یک Header | 401 از 0.122.0؛ قبلاً 403؛ "security classes" در یادداشت انتشار | apiKey در Header |
Security(get_current_user, scopes=[...]) | Dependency شما | کد شما تعیین میکند | افزودن Scope به عملیات |
پارامتر SecurityScopes | Scope همهٔ Dependantها | موضوعیت ندارد | موضوعیت ندارد |
auto_error=False روی Schemeها | — | بهجای استثنا None میدهد | همان |
راهحل / نحوهٔ استفاده: یک get_current_user پشت Aliasهای CurrentUser و AdminUser؛ Scope با Security؛ تست، get_current_user را Override کند، نه رشتهٔ Token را.
جایگزینی Dependency با app.dependency_overrides حیاتی
به زبان ساده: app.dependency_overrides دیکشنری معمولی است. Dependable اصلی را کلید و جایگزین را مقدار بگذارید؛ FastAPI هر جا آن گره در هر گراف باشد جایگزین را فراخوانی میکند. در پایان تست دیکشنری را پاک کنید.
بدفهمی رایج: «اصل اجرا میشود و Override خروجیاش را پردازش میکند.» نه اصل اجرا میشود و نه Sub-dependencyهای آن. مستندات: "You don't want the original dependency to run (nor any of the sub-dependencies it might have)." در اجرای واقعی با Override کردن get_current_user، درخواست /whoami بدون هیچ Header Authorization پاسخ ۲۰۰ گرفت چون oauth2_scheme اجرا نشد. Override خودش Dependable کامل است و پارامترهایش را از درخواست میخواند. جایگزین get_tenant با اعلان t: Query()، ورودی Tenant را از Header به Query برد؛ اجرای واقعی.
تعریف: "your FastAPI application has an attribute app.dependency_overrides, it is a simple dict. To override a dependency for testing, you put as a key the original dependency (a function), and as the value, your dependency override (another function)." همچنین "You can set a dependency override for a dependency used anywhere in your FastAPI application. The original dependency could be used in a path operation function, a path operation decorator (when you don't use the return value), a .include_router() call, etc." بازنشانی با "setting app.dependency_overrides to be an empty dict" است. در سازوکار 0.128.8، solve_dependencies برای هر گره dependency_overrides.get(original_call, original_call) را اجرا و از نتیجه Dependant تازه میسازد.
test_override_a_deep_sub_dependency_the_engine (real run)
1 engine = make_engine("sqlite:///<tmp>/test.db"); create_schema_and_seed(engine)
2 app.dependency_overrides[get_engine] = lambda: engine
3 POST /notes -> get_session(engine=<test engine>) (get_session itself still runs)
4 201; the row is in the file database
5 fixture teardown: app.dependency_overrides.clear()سناریوی واقعی: کاربر Fake بهجای ارائهدهندهٔ هویت؛ Engine تست؛ ساعت ثابت؛ Client پرداخت Fake؛ غیرفعالکردن بررسی API key در تست Route مدیریت؛ Mailer آزمایشی در Staging، هرچند تنظیمات راه بهتری است.
| Override | اثر | تست قطعهکد |
|---|---|---|
[get_current_user] = lambda: TESTER | Token لازم نیست؛ oauth2_scheme رد میشود | test_override_skips_the_original_and_its_sub_dependencies |
[get_engine] = lambda: engine | get_session واقعی روی Engine تست | test_override_a_deep_sub_dependency_the_engine |
[get_tenant] = tenant_from_query | Query خود Override خوانده میشود | test_override_can_declare_its_own_parameters |
[RoleChecker] = ... | نادیده؛ کلید گراف نیست | test_parameterised_instance_is_the_key_not_the_class |
[require_admin] = ... | Guard غیرفعال | همان تست |
[verify_api_key] و [request_context] | Dependency Router و سراسری عوض میشوند | test_router_and_global_dependencies_can_be_overridden |
.clear() | بازگشت گراف واقعی | test_clear_restores_the_real_graph |
راهحل / نحوهٔ استفاده: App factory و Fixture پاککنندهٔ Overrideها داشته باشید. بالاترین گره حذفکنندهٔ سیستم خارجی را عوض کنید: کاربر بهجای Token؛ Engine بهجای Session وقتی منطق Session باید واقعی بماند. Fixture کامل پایگاه داده در تست FastAPI است.
منابع Lifespan در برابر Dependency هر درخواست: Engine، Session و Singleton حیاتی
به زبان ساده: بعضی اشیا گران و برای استفادهٔ همزمان Threadها امناند و باید یک بار در هر پردازه (Process) وجود داشته باشند: Engine در SQLAlchemy با Pool اتصال (Connection)، یک httpx.AsyncClient، تنظیمات بارگذاریشده یا مدل ML. آنها را در چرخهٔ عمر (Lifespan) بسازید. اشیای دیگر ارزاناند و نباید مشترک باشند: Session بهعنوان واحد کار (Unit of work) با تراکنش (Transaction) مستقل و کاربر جاری. آنها در Dependency برای هر درخواست ساخته میشوند. Dependency، Singleton را میخواند؛ Singleton چیزی از درخواست نمیداند.
بدفهمی رایج: «یک Session سراسری مثل Engine یک Singleton است.» Session یک Transaction و نقشهٔ هویت (Identity map) نگه میدارد؛ اشتراک آن Transaction همهٔ درخواستها را به هم گره میزند. برنامهٔ قبل نتیجه را نشان میدهد: یک IntegrityError و سپس شکست درخواست نامرتبط با PendingRollbackError؛ اجرای واقعی. اشتباه معکوس، ساخت Engine در هر درخواست است: هر بار Pool تازه باز میکند و سودی ندارد.
تعریف: راهنمای SQLAlchemy برای وب: "the basic pattern is create a Session at the start of a web request, call the Session.commit() method at the end of web requests that do POST, PUT, or DELETE, and then close the session at the end of web request". Starlette: "The lifespan has the concept of state, which is a dictionary that can be used to share the objects between the lifespan, and the requests" و "The state received on the requests is a shallow copy of the state received on the lifespan handler." دسترسی دیکشنری request.state["http_client"]، "was introduced in Starlette 0.52.0 (January 2026)"؛ نسخهٔ ثابت 0.49.3 از Attribute استفاده میکند. FastAPI: "If you provide a lifespan parameter, startup and shutdown event handlers will no longer be called."
worker process start (Uvicorn, real log: "Application startup complete.")
1 lifespan: engine = make_engine(DATABASE_URL); create_schema_and_seed(engine)
2 app.state.engine = engine; yield {"audit_log": []}
3 request 1: get_engine(request) -> app.state.engine; get_session -> Session(engine) ... close()
4 request 2: same engine, a new Session
5 shutdown ("Application shutdown complete."): engine.dispose()
6 --workers 4: steps 1-5 happen in each of 4 processes: 4 engines, 4 poolsسناریوی واقعی: Pool با ۱۰ Connection برای هر Worker و چهار Worker در برابر پایگاه داده با ظرفیت ۵۰؛ یک httpx.AsyncClient برای هر Worker برای بازاستفادهٔ Connection به API شریک؛ مدل بارگذاریشده یک بار در هر Worker؛ Engineهای مختص Tenant در دیکشنری app.state که Dependency مربوط به Tenant از میانشان انتخاب میکند.
| شیء | عمر | محل ساخت | تزریق از طریق |
|---|---|---|---|
Engine و Pool | Process | Lifespan | get_engine با خواندن app.state |
Session | درخواست | get_session با yield | SessionDep |
httpx.AsyncClient | Process | Lifespan با async with | Dependency خوانندهٔ request.state |
| تنظیمات | Process | Lifespan یا تابع Cacheشده | SettingsDep |
| کاربر جاری | درخواست | get_current_user | CurrentUser |
| فهرست Audit قطعهکد | Process، هر اجرای Lifespan | Lifespan state | request.state.audit_log |
راهحل / نحوهٔ استفاده: قاعدهٔ «Engine در Lifespan، Session در Dependency». هر شیء سراسری Process از Dependency در دسترس باشد تا Override شود. اندازهٔ Pool × تعداد Worker ≤ سقف Connection پایگاه داده؛ FastAPI در Production.
max_concurrency: محدودکردن فراخوانی همزمان، از 0.163.0 و پس از نسخهٔ قطعهکد تکمیلی
به زبان ساده: از FastAPI 0.163.0، Depends(get_session, max_concurrency=5) حداکثر پنج فراخوانی فعال همزمان اجازه میدهد. درخواست ششم بدون اشغال Thread مربوط به Worker منتظر بستهشدن یک Session میماند.
بدفهمی رایج: «max_concurrency اندازهٔ Pool پایگاه داده را محدود میکند.» FastAPI Pool را نمیشناسد: "FastAPI doesn't know the size of your database connection pool". محدودیت بهازای شیء Depends، Event loop و Process مربوط به Worker است: "two worker processes with this dependency could have up to ten sessions open between them."
تعریف: راهنمای پیشرفته: "Now, up to five requests can have a database session open through this dependency at the same time. If another request needs a session, it waits until one of those sessions is closed. While waiting, it doesn't occupy a worker thread". برای Dependency مولد، "The session counts toward the limit until the exit code finishes closing it"؛ پس scope مهم است. هشدار بنبست (Deadlock): اگر همان Depends(get_session, max_concurrency=1, use_cache=False) مشترک را دو بار در یک درخواست مصرف کنید، منتظر خودش میماند.
SessionDep = Annotated[Session, Depends(get_session, max_concurrency=5)] (0.163.0+, not run)
1 requests 1-5: session opened
2 request 6: waits (no thread held)
3 request 1 finishes; teardown closes its session (after the response with scope="request")
4 request 6 proceedsسناریوی واقعی: محافظت پایگاه دادهٔ کوچک در برابر موج درخواست؛ محدودکردن فراخوانی API شریک دارای Rate limit داخل یک Worker؛ جایگزینی Dependency دستنویس با asyncio.Semaphore.
| تنظیم | اشتراک محدودیت |
|---|---|
یک Alias با max_concurrency=5 در همهجا | همهٔ آن Routeها |
نوشتن Depends(get_session, max_concurrency=5) در هر Route | هر Route مستقل |
| دو App در یک Event loop با همان Alias | هر دو برنامه |
| دو Process مربوط به Worker | مشترک نیست؛ هرکدام 5 |
راهحل / نحوهٔ استفاده: فقط پس از ارتقا به 0.163.0 یا جدیدتر؛ محدودیت روی Alias و کمتر از اندازهٔ Pool باشد. برای پاسخ کند، scope="function" بهتر است.
ضدالگوها: وضعیت سراسری تغییرپذیر، Service locator و تزریق بیشازحد حیاتی
به زبان ساده: سه راه برای ازبینبردن مزیت DI: شیء ماژولی حامل دادهٔ هر درخواست؛ Registry که Route هنگام اجرا از آن میپرسد؛ امضایی با پانزده Dependency که جایش باید یک شیء سرویس باشد.
بدفهمی رایج: «مکانیاب سرویس (Service locator) همان DI با نام بهتر است.» ظاهراً شبیه است چون Route خودش چیزی نمیسازد. مرز Fowler: "The key difference is that with a Service Locator every user of a service has a dependency to the locator." در برنامهٔ قبل، Route به ServiceLocator و کلیدهای رشتهای وابسته است؛ امضا نیازهایش را نمیگوید. تست باید Registry را تغییر دهد و برگرداند.
تعریف: وضعیت سراسری تغییرپذیر (Global mutable state) شیء سطح ماژولی است که محتوا با درخواست یا کاربر عوض میشود: Session مشترک، Cache دیکشنری بدون قفل (Lock)، متغیر سراسری «کاربر جاری». تعریف Service locator از Fowler: "object that knows how to get hold of all of the services that an application might need". تزریق بیشازحد (Over-injection) یعنی Route همهٔ Repository و Clientها را مستقیم بگیرد و هماهنگسازی متعلق به سرویس را انجام دهد. راهحل، تزریق یک سرویس ساختهشده از Dependencyهاست.
over-injected route one service dependency
1 def checkout(s: SessionDep, u: CurrentUser, def get_checkout(s: SessionDep, pay: PaymentDep,
2 pay: PaymentDep, stock: StockDep, mail: MailDep, stock: StockDep, mail: MailDep) -> CheckoutService
3 tax: TaxDep, audit: AuditDep, flags: FlagsDep): def checkout(svc: Annotated[CheckoutService, Depends(get_checkout)],
4 ... 80 lines of orchestration user: CurrentUser): return svc.run(user)
5 tests: override 8 dependencies tests: override get_checkout, or its partsسناریوی واقعی: متغیر ماژولی «Tenant جاری» که در همزمانی اطلاعات بین درخواستها نشت میدهد؛ Helper به نام get_service("mailer") که به Locator بزرگ تبدیل شده؛ Route با دوازده پارامتر که کسی نمیتواند تستش کند.
| ضدالگو | نشانه | اصلاح |
|---|---|---|
Session سراسری | PendingRollbackError پس از یک شکست؛ دادهٔ مشترک درخواستها | Dependency مولد به نام get_session |
| «کاربر/Tenant جاری» سراسری | دادهٔ کاربر اشتباه در همزمانی | request.state یا Dependency |
| Service locator | نیازهای پنهان؛ تغییر Registry در تست | اعلان با Depends |
| Engine در هر درخواست | Pool تازه و طوفان Connection | Engine در Lifespan |
| Over-injection | Route با 10+ Dependency | کلاس سرویس ساختهشده با Dependency |
| منطق کسبوکار داخل Dependency | منطق فقط از HTTP تستپذیر است | تابع یا کلاس معمولیِ تزریقشده |
Depends در عمق لایهٔ Domain | کد Domain، FastAPI را import میکند | فقط لایهٔ وب از Depends استفاده کند |
راهحل / نحوهٔ استفاده: Depends در مرز، یعنی Route و dependencies.py بماند. سرویس دامنه (Domain) کلاس معمولی باشد که در __init__ همکار میگیرد؛ همان Constructor injection. یک Dependency سرویس را از اجزای درخواست بسازد. جهت پیکانها میان لایهها در معماری Clean، Hexagonal و Onion است.
سه Dependency کامل: صفحهبندی، Authentication و Tenant مهم
به زبان ساده: تقریباً هر سرویس این سه را میخواهد. صفحهبندی (Pagination) یک Dependency کلاسی با Query معتبر است؛ Authentication زنجیرهٔ Bearer token، کاربر و Scopeهاست؛ Tenant یک Header معتبر است که با کاربر ترکیب میشود تا «کاربر مجاز در این Tenant» بسازد.
بدفهمی رایج: «فیلتر Tenant را در Route اضافه میکنیم.» فراموشی یک Route باعث نشت داده میشود. وقتی Tenant از Dependency لازم برای همهٔ Routeهای مربوط به Tenant، یعنی TenantUser، میآید، بررسی تصادفی جا نمیافتد. جداسازی ردیفی در پایگاه داده لایهٔ دوم و قویتر است.
تعریف: مثال Pagination، کلاس Pagination با page ≥ 1، 1 ≤ size ≤ 100 و ویژگی offset است. مثال Authentication زنجیرهٔ oauth2_scheme → get_current_user(SecurityScopes) → CurrentUser/WriterUser است. مثال Tenant، get_tenant با X-Tenant-ID و Regex، سپس get_tenant_user است که اختلاف Tenant کاربر را با ۴۰۳ رد میکند.
GET /notes Bearer alice-token X-Tenant-ID: globex (real run)
1 Pagination(page=1, size=20)
2 get_tenant -> "globex"
3 oauth2_scheme -> "alice-token"; get_current_user -> alice (tenant acme)
4 get_tenant_user: acme != globex -> 403 "User does not belong to this tenant"
5 the SELECT never runsسناریوی واقعی: SaaS سازمانی با X-Tenant-ID یا زیردامنه؛ Pagination مبتنی بر Cursor بهجای Offset برای جدول بزرگ، صفحهبندی؛ Rate limit هر Tenant با کلید حاصل از Dependency آن.
| مثال | نوع Dependency | ورودی | شکست |
|---|---|---|---|
| Pagination | کلاس، Depends() | Queryهای page و size | 422 |
| Authentication | نمونهٔ Callable + تابع + Security | Header به نام Authorization و Scope | 401 / 403 |
| Tenant | تابع + گراف Sub-dependency | Header به نام X-Tenant-ID و کاربر | 422 / 403 |
| Guard مدیر | کلاس Callable در Decorator | نقشهای کاربر | 403 |
| Feature flag | کارخانهٔ Closure | app.state.features | 404 |
| API key | Dependency Router | Header به نام X-API-Key | 422 / 403 |
راهحل / نحوهٔ استفاده: شکلها را از app/deps.py بردارید؛ در Production جدول Token ساختگی را با بررسی JWT جایگزین کنید؛ احراز هویت FastAPI. برای Tenant، Guard سطح پایگاه داده هم اضافه کنید.
سازوکار
کار FastAPI هنگام import و هر درخواست مهم
هنگام اعمال Decorator مثل @router.get(...)، FastAPI با get_dependant یک Dependant برای Path operation میسازد. get_typed_signature روی تابع، Annotation رشتهای را با call.__globals__ حل میکند. هر پارامتر که Metadata در Annotated یا مقدار پیشفرضش Depends/Security باشد، به Sub-dependant بازگشتی تبدیل میشود. dependencies=[...] برنامه، Router و Decorator بهصورت Sub-dependant بینام به ابتدای فهرست اضافه میشوند. هر Dependant کلید cache_key برابر (call, scopes_for_cache, computed_scope) دارد؛ computed_scope برای Generatorها "request" است مگر scope= خلافش را بگوید. در هر درخواست Handler دو AsyncExitStack، یکی برای درخواست و یکی برای تابع، باز میکند و solve_dependencies را صدا میزند:
solve_dependencies(dependant, request, dependency_cache={}) (fastapi 0.128.8, dependencies/utils.py)
1 for sub in dependant.dependencies: # declaration order: app, router, decorator, params
2 call = app.dependency_overrides.get(sub.call, sub.call) # override lookup on every node
3 solve_dependencies(sub or its override) # its own sub-dependencies first (recursion)
4 if sub.use_cache and sub.cache_key in cache: value = cache[key]
5 elif generator: value = await stack.enter_async_context(cm) # request stack, or function stack if scope="function"
6 elif coroutine: value = await call(**values)
7 else: value = await run_in_threadpool(call, **values)
8 cache.setdefault(sub.cache_key, value)
9 then read path, query, header, cookie params and the body of this dependant; collect errors
10 errors -> RequestValidationError (422); else call the route; exit function stack; send; exit request stackدو پیامد قابل مشاهدهاند. همهٔ خطاهای اعتبارسنجی (Validation) پیش از Route در یک ۴۲۲ جمع میشوند؛ اما Dependencyهایی که ورودی خودشان معتبر است قبلاً اجرا شدهاند. در اجرای واقعی runs/probe6-output.txt، Dependency ثبت Log اجرا شد و بعد ۴۲۲ برای ?n=abc آمد. تغییر ترتیب کمک نمیکند: حلقه خطای Sub-dependency را ثبت میکند و با continue سراغ بعدی میرود؛ پس Dependency اثر جانبیِ معتبر حتی بعد از گره خراب هم اجرا میشود؛ test_validation_error_does_not_stop_a_sibling_side_effect. چیزی که جلوی اجرا را میگیرد لینک Dependency است: اگر یکی از Sub-dependencyهای خود Dependant خطا داشته باشد، Dependant اجرا نمیشود. بنابراین اثر جانبی که با Depends به ورودی معتبر وابسته است روی ۴۲۲ کنار گذاشته میشود؛ test_side_effect_that_depends_on_the_input_is_skipped. اثر جانبی را در Route بگذارید یا به ورودی لازم وابسته کنید. نکتهٔ دوم: مقدار Dependency از Cache میآید، ولی Sub-dependencyهایش همچنان پیمایش میشوند؛ آنها هم Cache دارند، پس دوباره فراخوانی نمیشوند.
جریان درخواست POST /notes در قطعهکد تکمیلی
POST /notes Authorization: Bearer alice-token X-Tenant-ID: acme X-Request-ID: req-1 (real run)
1 Uvicorn -> Starlette router -> APIRoute for POST /notes
2 request_context: request.state.request_id = "req-1"; response header X-Request-ID
3 get_engine -> app.state.engine; get_session -> Session, yield (request stack)
4 oauth2_scheme -> "alice-token"; get_current_user[notes:write] -> alice
5 get_current_user[notes:read] (second cache key) -> alice; get_tenant -> "acme"; get_tenant_user -> alice
6 body {"title": "new"} -> NoteIn; BackgroundTasks; Request
7 create_note: session.add; session.commit() -> 201 {"id": 7, ...}
8 response sent (201, X-Request-ID: req-1)
9 background task write_audit(log, "req-1", 7)
10 get_session teardown: session.close()متن دقیق خطاها، هشدارها و خروجیها حیاتی
همهٔ سطرهای زیر خروجی اجرای قطعهکد با FastAPI 0.128.8، Starlette 0.49.3، Pydantic 2.13.5، SQLAlchemy 2.0.58 و Uvicorn 0.39.0 هستند.
| محرک | وضعیت | خروجی دقیق |
|---|---|---|
نبود Header به نام Authorization در OAuth2PasswordBearer | 401 | {"detail":"Not authenticated"}، www-authenticate: Bearer |
Bearer nope | 401 | {"detail":"Invalid token"} از get_current_user |
| نبود Scope لازم | 403 | {"detail":"Missing scope: notes:write"}، www-authenticate: Bearer scope="notes:write" |
X-Tenant-ID: Bad_Tenant | 422 | {"type":"string_pattern_mismatch","loc":["header","x-tenant-id"],"msg":"String should match pattern '^[a-z][a-z0-9-]{1,31}$'",...} |
?page=0 | 422 | {"type":"greater_than_equal","loc":["query","page"],"msg":"Input should be greater than or equal to 1","input":"0","ctx":{"ge":1}} |
| نبود Header مربوط به Dependency Router | 422 | {"type":"missing","loc":["header","x-api-key"],"msg":"Field required","input":null} |
| یادداشت تکراری با Commit در Route | 409 | {"detail":"A note with this title exists"} |
| برنامهٔ قبل، درخواست پس از Commit شکستخورده | 500 | PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. |
Dependency کلاسی همراه from __future__ import annotations | 500 هنگام درخواست | PydanticUserError: TypeAdapter[typing.Annotated[ForwardRef("Annotated[int, Query(ge=1, description='1-based page number')]"), ...]] is not fully defined |
نمونهٔ Callable یعنی RoleChecker همراه from __future__ import annotations | 422 | {"type":"missing","loc":["query","user"],"msg":"Field required","input":null} |
except ValueError: بدون raise در Dependency مولد | 500 | Internal Server Error؛ سمت سرور FastAPIError: Response not awaited. There's a high chance that the application code is raising an exception and a dependency with yield has a block with a bare except...؛ ValueError اصلی گم شده |
استثنای پس از yield در روند موفقیت | 200 برای Client | RuntimeError: commit failed after the response دوباره توسط TestClient پرتاب میشود |
TestClient(create_app()) بدون with و سپس GET /notes | — | AttributeError: 'State' object has no attribute 'engine'؛ Lifespan اجرا نشده |
| Log در Uvicorn برای 422 در Dependency Router | — | INFO: 127.0.0.1:49252 - "GET /admin/stats HTTP/1.1" 422 Unprocessable Entity |
| SQL هنگام Teardown درخواست خواندن | — | INFO sqlalchemy.engine.Engine ROLLBACK |
حل مسائل رایج
| خطا | نشانه | اصلاح | هزینه |
|---|---|---|---|
Session سراسری | یک شکست همهٔ درخواستهای بعدی را خراب میکند؛ اشتراک داده | Dependency مولد به نام get_session و SessionDep | 15 خط |
Commit پس از yield | Client با وجود شکست Commit، پاسخ 200 میگیرد | Commit در Route؛ Dependency فقط Rollback و Close | جابهجایی یک خط |
except بدون raise | 500 با علت گمشده؛ Log فقط FastAPIError: Response not awaited | except: rollback(); raise | یک واژه |
| Authentication کپیشده در هر Route | فراموششدن بررسی در یک Route | Alias به نام CurrentUser و Dependency Router برای گروه | بازآرایی |
| فیلتر Tenant در هر Route | نشت داده میان Tenantها | TenantUser در هر Route مربوط به Tenant و Guard پایگاه داده | کم |
| Header در Dependency سراسری | نبود Header روی 401/404/422 | Middleware برای Header همیشهحاضر | کم |
Dependency کلاس یا نمونهٔ Callable در ماژول __future__ | 500 برای کلاس یا 422 جعلیِ missing برای Query در قطعهکد | حذف Future import در آن ماژول یا استفاده از تابع | هیچ |
| کلید Override برابر کلاس | نادیدهگرفتن بیصدای Override | کلید همان نمونهٔ Route | هیچ |
| نشت Override میان تستها | تست وابسته به ترتیب | App factory و Fixture پاککنندهٔ دیکشنری | Fixture |
| Task پسزمینه با Session درخواست | در یک نسخه کار میکند، در دیگری نه | شناسه بدهید؛ Session تازه داخل Task | کم |
| Engine برای هر درخواست | طوفان Connection و درخواست کند | Engine در Lifespan و خواندن app.state در Dependency | کم |
Blocking در Dependency با async def | توقف همهٔ درخواستهای Worker | Dependency با def یا کتابخانهٔ async | کم |
| 15 پارامتر تزریقی | هماهنگسازی تستناپذیر در Route | یک Dependency سرویس | بازآرایی |
یک Session برای هر درخواست، با پاکسازی همیشگی
تفاوت before.SESSION و get_session تمام درس است. Dependency مولد به هر درخواست واحد کار (Unit of work) مستقل میدهد، روی هر استثنا Rollback میکند و در finally میبندد؛ شکست یک درخواست به بعدی نشت نمیکند. Route، Commit میکند تا کد وضعیت نتیجهٔ آن را منعکس کند. تست test_create_commits_in_route_and_background_task_gets_ids هر دو را نشان میدهد: ۴۰۹ برای تکراری و سپس ۲۰۰ سالم در درخواست بعد.
Authentication و Tenant که فراموش نمیشوند
راه امن را کوتاهترین راه کنید. نوشتن TenantUser از خواندن دستی Headerها کوتاهتر است و رفتار ۴۰۱، ۴۰۳ و ۴۲۲ را همراه دارد. Route مدیریت Guard را از Router میگیرد؛ Route تازه هم بدون نیاز به یادآوری محافظت میشود. تست OpenAPI نشان میدهد مستندات نیز با رفتار واقعی هماهنگ میمانند.
تست بدون Monkeypatch
هر جزء خارجی، مثل کاربر، Engine، ساعت و HTTP client از Dependency قابل دسترسی است؛ پس هر تست دقیقاً یک مدخل دیکشنری را عوض میکند. App factory برنامهٔ مستقل میدهد و Fixture، Overrideها را پاک میکند. برنامهٔ قبل برای هر تعویض سراسری try/finally میخواهد؛ برنامهٔ بعد یک خط.
آزادکردن منابع در زمان درست
زمان Teardown نسخهٔ خود را بشناسید؛ جدول. از 0.121.0+ برای منبعی که فقط جهت Authorization پاسخ کند یا Streaming لازم است، scope="function" بگذارید. ارتقا به 0.163.0 یا جدیدتر، max_concurrency را برای حفاظت از Pool کوچک اضافه میکند.
انتخاب
| وضعیت | انتخاب | تکنیک تکمیلی | دلیل |
|---|---|---|---|
| Route مقدار میخواهد | Dependency پارامتری با Alias | Alias مبتنی بر Annotated در dependencies.py | تایپدار، Cacheشده و مستند |
| Route فقط بررسی میخواهد | dependencies=[...] در Decorator | بررسی ارزان اول | بدون پارامتر بیمصرف |
| تمام Routeهای گروه بررسی میخواهند | APIRouter(dependencies=...) | یا include_router(..., dependencies=...) | فراموش نمیشود |
| هر Route مطابق لازم دارد | FastAPI(dependencies=...) | ارزان نگه دارید | پیش از همه |
| هر درخواست، شامل 404 | Middleware | Dependency نباشد | Dependency به Route مطابق نیاز دارد |
| منبع همعمر Process | Lifespan و app.state یا Lifespan state | Dependency خواننده | ساخت یک بار در هر Worker |
| منبع هر درخواست با پاکسازی | Dependency مولد | finally | Teardown تضمینشده |
| منبع فقط برای Authorization | Depends(..., scope="function") | 0.121.0+ | آزادسازی پیش از پاسخ |
| بررسی قابل تنظیم | نمونهٔ کلاس Callable | نمونه در سطح ماژول | Override با نمونه |
| مقدار تازه در هر مصرف | use_cache=False | بهندرت | عبور از Cache درخواست |
| محدودکردن مصرف همزمان | max_concurrency از 0.163.0+ | همان Alias در همهجا | محدودیت مشترک |
| سرویس Domain | کلاس معمولی با Constructor injection | یک Dependency سازنده | Domain مستقل از Framework |
| گراف بزرگ اشیا و چند برنامه | کتابخانهٔ DI container | فقط وقتی Depends مشکلساز شده | مفهوم اضافه برای یادگیری |
Depends در برابر DI container در Laravel و Fx
| پرسش | Depends در FastAPI | Container در Laravel و Uber Fx |
|---|---|---|
| محل Binding | امضا و Alias | Provider و ماژول با bind و fx.Provide |
| عمر پیشفرض | هر درخواست، Cache همان درخواست | هر Resolve با bind، Singleton با singleton، هر Lifecycle با scoped |
| Singleton | Lifespan و app.state | singleton() و Singletonهای مدیریتشدهٔ Fx |
| Interface به پیادهسازی | انتخاب تابع ورودی | Binding صریح Interface |
| ورودی درخواست، Query و Header | خواندن و Validation در Dependency | وظیفهٔ Container نیست |
| مستندسازی | OpenAPI از ورودی Dependency | ندارد |
| تعویض در تست | app.dependency_overrides | در Laravel، $this->app->instance(...)؛ در Fx ساخت App تست با سازندهٔ Fake در fx.Provide |
| خارج HTTP، CLI و Worker | نه؛ درخواست لازم است | بله |
برای Worker پسزمینه و CLI که درخواست ندارند، همان سرویسها را با Constructor injection معمولی در تابع ترکیب کوچک بسازید؛ Dependencyها هم از آن بازاستفاده کنند.
در معماری: از یک پردازه (Process) تا سیستم توزیعشده
یکپارچه (Monolith): یک Process و یک پایگاه داده
یک برنامهٔ FastAPI، یک app/dependencies.py، یک Engine در Lifespan، SessionDep همهجا و CurrentUser از یک Dependency احراز هویت. قطعهکد این فصل همین یکپارچه (Monolith) است. Backend فروشگاه هم همین شکل را دارد: SessionDep برای کاتالوگ و سفارش، CurrentUser برای حساب، Router مدیریت پشت AdminUser، یک httpx.AsyncClient در Lifespan برای ارائهدهندهٔ پرداخت، و Dependency مربوط به Tenant یا فروشگاه اگر چند ویترین را سرویس دهد. تست کاربر و Engine را Override میکند.
یکپارچهٔ ماژولار (Modular monolith) و چند پایگاه داده
در یکپارچهٔ ماژولار (Modular monolith)، هر ماژول کاتالوگ، سفارش یا صورتحساب مالک Router، ماژول Dependency و کلاس سرویس خودش است. Dependency مشترک Session، کاربر و Tenant در بستهٔ core قرار دارد که ماژولها import میکنند؛ هرگز برعکس. دو پایگاه داده یعنی دو Engine در Lifespan و دو Dependency مانند CatalogSessionDep و BillingSessionDep. Route مصرفکنندهٔ هر دو، دو Session باز میکند و بینشان تراکنش توزیعشده (Distributed transaction) وجود ندارد؛ اگر نوشتن باید هر دو پایگاه داده را دربر بگیرد، از Outbox یا Saga استفاده کنید. Dependency Router مرز ماژول را در لبه اعمال میکند؛ مثلاً Route صورتحساب، Scope به نام billing لازم دارد.
ریزسرویسها (Microservices)
DI در مرز Process متوقف میشود. داخل هر ریزسرویس (Microservice) همین الگوها برقرارند؛ میان سرویسها Dependency یک Client شبکه است. برای هر سرویس پاییندستی کلاس Client تایپدار بسازید که یک بار در Lifespan ایجاد شود تا Connection بازاستفاده شود و از Dependency به درخواست تزریق شود. Dependency میتواند Context درخواست را ببندد: شناسه را از request.state منتقل کند، Token فراخواننده را بفرستد یا با Token سرویس عوض کند و مهلت (Deadline) هر درخواست را اعمال کند. جریان مثال: POST /orders → OrdersClientDep → PaymentsClientDep با Header به نام Idempotency-Key مشتق از شناسهٔ سفارش. تست Client را با Fake عوض میکند و تست قرارداد (Contract test)، Fake را با API واقعی میسنجد. Authentication در Microservice معمولاً بررسی محلی JWT در get_current_user با کلیدهای صادرکنندهٔ Cacheشده در Lifespan است، نه تماس با ارائهدهندهٔ هویت در هر درخواست.
دادهٔ توزیعشده (Distributed data): Replica، Cache، Shard و چند منطقه
تصمیم هدایت درخواست در Dependency قرار میگیرد. ReadSessionDep میتواند Engine نسخهٔ خواندنی (Replica) و WriteSessionDep، Engine اصلی را انتخاب کند. قاعدهٔ خواندن نوشتهٔ خود (Read your writes) هم میتواند اینجا باشد؛ مثلاً «تا پنج ثانیه پس از نوشتن کاربر، از Primary بخوان»، با کلید کاربر. برای پایگاه دادهٔ بخشبندیشده (Sharded) یا مختص Tenant، Dependency ابتدا Tenant را حل میکند و Engine را از دیکشنری ساختهشده در Lifespan برمیدارد: app.state.engines[tenant.shard]. Client مربوط به Redis منبع سراسری Process در Lifespan است؛ Cache هر درخواست همان Cache داخلی Dependency است. هرچه در حافظهٔ Process باشد، شامل app.state، Lifespan state و فهرست Audit قطعهکد، برای هر Worker و Replica یک نسخه دارد. شمارنده و Cache واقعاً مشترک باید در Redis یا PostgreSQL باشد. انتخاب سطح جداسازی Sessionها در سطوح جداسازی است.
رشد بار (Scaling path): ۱×، ۱۰× و ۱۰۰×
| بار | چه تغییر میکند | شیوهٔ Dependency |
|---|---|---|
| 1×، یک Process | پیشفرضها کافیاند | Engine در Lifespan، SessionDep، Authentication و Tenant با Dependency و Override در تست |
| 10×، چند Worker یا Replica | Poolها چندبرابر و وضعیت Processها متفاوت میشوند | اندازهٔ Pool × Worker ≤ سقف DB؛ وضعیت مشترک در app.state نباشد؛ scope="function" برای پاسخ کند؛ Thread pool متناسب با Dependency sync |
| 100×، سرویس زیاد و Fan-out بالا | تأخیر دنباله، اتمام Pool و هزینهٔ Authentication | Session و Client ناهمگام سرتاسری؛ JWT محلی با کلید Cacheشده؛ max_concurrency از 0.163.0+ یا Semaphore برای هر پاییندست؛ انتخاب Replica در Dependency مربوط به Session؛ انتقال شناسهٔ درخواست با Middleware |
آزمایشگاه
همهٔ فرمانها از docs/snippets/python/dependency-injection-depends/ اجرا میشوند. خروجیهای «واقعی» با CPython 3.9.6 روی macOS و نسخههای ثابت تولید شدند. Python 3.12 با FastAPI جاری اجرا نشده و تأییدنشده است؛ دستکم شمارهٔ نسخهها متفاوت خواهد بود و تستهای تثبیتکنندهٔ رفتار 0.128.8، یعنی test_gotchas.py و ترتیب رویدادهای test_lifecycle.py، ممکن است در انتشارهای بعد تغییر کنند.
۱. نصب و اجرای تستها، واقعی
python3 -m venv ~/venvs/did # keep the venv outside the repo (.venv/, *.egg-info are not git-ignored)
~/venvs/did/bin/pip install -e '.[test]'
source ~/venvs/did/bin/activate
export PYTHONDONTWRITEBYTECODE=1 # no __pycache__; pyproject sets -p no:cacheprovider
pytest
# ............................................ [100%]
# 44 passed in 0.41s
pytest -v # -v cancels the -q from pyproject: one line per file
# tests/test_before.py ..... [ 11%]
# tests/test_gotchas.py .. [ 15%]
# tests/test_lifecycle.py ............ [ 43%]
# tests/test_main.py ................ [ 79%]
# tests/test_openapi.py ... [ 86%]
# tests/test_overrides.py ...... [100%]
# 44 passed in 0.43sنسخههای حلشدهٔ آن نصب در requirements.lock پروژهاند؛ pip install -r requirements.lock همان نصب را بازتولید میکند. گزینههای pytest شامل -q هستند؛ بنابراین هر تست یک نقطه است. با uv روی Python 3.12+، فرمان uv run --extra test pytest انتظار میرود کار کند، اما اجرا نشده چون uv روی ماشین Build نصب نیست.
۲. مشاهدهٔ ترتیب رویدادها، واقعی
pytest tests/test_lifecycle.py -k "order or teardown or scope"
# ... [100%]
# 3 passed, 9 deselected in 0.03s
python -c "from fastapi.testclient import TestClient; from app import lifecycle as L; TestClient(L.app).get('/teardown'); print(L.EVENTS)"
# ['app dependency', 'a setup', 'b setup', 'c setup', 'route', 'response.start 200',
# 'background task ran', 'c teardown', 'b teardown', 'a teardown']سپس در کپی آزمایشی، Depends(dep_c) را در teardown() به Depends(dep_c, scope="function") تغییر دهید و خط python -c را دوباره اجرا کنید؛ نتیجهٔ واقعی:
# ['app dependency', 'a setup', 'b setup', 'c setup', 'route', 'c teardown',
# 'response.start 200', 'background task ran', 'b teardown', 'a teardown']فقط dep_c به پیش از پاسخ منتقل شد. Sub-dependencyهای دارای Scope درخواست، یعنی dep_b و dep_a، همچنان پس از پاسخ و Background task بسته میشوند. قاعدهٔ مستندات همین است: "a dependency with scope of 'function' can have dependencies with scope of 'function' and scope of 'request'". اما Dependency با Scope درخواست فقط میتواند به Dependency با همان Scope وابسته باشد.
۳. اجرای سرور و فراخوانی آن، واقعی
uvicorn app.main:app --port 18917
curl -i -H "Authorization: Bearer alice-token" -H "X-Tenant-ID: acme" "http://127.0.0.1:18917/notes?page=1&size=2"
# HTTP/1.1 200 OK
# x-request-id: d91bb7b3f7a149b9a29c901442ffd543
# [{"id":1,"title":"acme note 1","owner":"alice"},{"id":2,"title":"acme note 2","owner":"alice"}]
curl -i -H "X-Tenant-ID: acme" http://127.0.0.1:18917/whoami
# HTTP/1.1 401 Unauthorized
# www-authenticate: Bearer
# {"detail":"Not authenticated"} <- no x-request-id on the error response
curl -s http://127.0.0.1:18917/admin/stats
# {"detail":[{"type":"missing","loc":["header","x-api-key"],"msg":"Field required","input":null}]}
curl -s -H "X-API-Key: admin-key" http://127.0.0.1:18917/admin/stats
# {"acme":5,"globex":1}Log این اجرای Uvicorn: یک بار Application startup complete. برای یک Lifespan، چهار خط دسترسی با 200، 401 Unauthorized، 422 Unprocessable Entity و 200، سپس با Ctrl+C پیام Application shutdown complete.؛ Engine آزاد شد. نشانی http://127.0.0.1:18917/docs را باز کنید. دکمهٔ Authorize از OAuth2PasswordBearer میآید و Scopeهای notes:read و notes:write را نشان میدهد. page، size و X-Tenant-ID روی GET /notes و X-API-Key روی هر دو Route مدیریت دیده میشوند.
۴. خرابکردن عمدی، واقعی
pytest tests/test_before.py -k poisons # asserts the 500 on the request after the IntegrityError
# . [100%]
# 1 passed, 4 deselected in 0.02s
pytest tests/test_gotchas.py -rA
# PASSED tests/test_gotchas.py::test_class_dependency_with_postponed_annotations_fails_at_request_time
# PASSED tests/test_gotchas.py::test_exception_after_yield_cannot_change_a_sent_response
# 2 passed in 0.01sسپس در کپی آزمایشی، from __future__ import annotations را بالای app/deps.py، بعد از Docstring، اضافه و برنامه را فراخوانی کنید؛ اجرای واقعی در runs/future-annotations-deps.txt:
# DELETE /notes/1 (RoleChecker instance): 422 {"detail":[{"type":"missing","loc":["query","user"],"msg":"Field required","input":null}]}
# GET /notes (Pagination class): 500 Internal Server ErrorTraceback خطای ۵۰۰ با PydanticUserError ... is not fully defined تمام میشود؛ در runs/forwardref-class-dependency-error.txt ذخیره شده است. این دام همینطور پیدا شد.
۵. Override در REPL، واقعی
python - <<'PY'
from fastapi.testclient import TestClient
from app.main import create_app
from app.deps import User, get_current_user
app = create_app()
app.dependency_overrides[get_current_user] = lambda: User(name="test", tenant="acme")
with TestClient(app) as c:
print(c.get("/whoami", headers={"X-Tenant-ID": "acme"}).json()["name"])
PY
# test <- no Authorization header was sent; oauth2_scheme never ranبرای توسعهدهندگان PHP/Laravel
Laravel همین مسئله را با ظرف (Container) حل میکند؛ تفاوت شکل، مهمترین نکتهٔ انتقال تجربه است. مستندات: "The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are 'injected' into the class via the constructor or, in some cases, 'setter' methods." بستنها (Bindings) را در Service provider ثبت میکنید: bind در هر Resolve شیء تازه میسازد و "The singleton method binds a class or interface into the container that should only be resolved one time". همچنین "The scoped method binds a class or interface into the container that should only be resolved one time within a given Laravel request / job lifecycle". این نمونهها "will be flushed whenever the Laravel application starts a new 'lifecycle', such as when a Laravel Octane worker processes a new request". نزدیکترین معادل FastAPI برای singleton، Lifespan؛ برای scoped، Dependency Cacheشده؛ و برای bind، Dependency با use_cache=False است.
Laravel پارامترهای دارای Type hint در سازنده و متد را خودکار حل میکند، یعنی "zero configuration resolution". Contextual binding (بستن وابسته به زمینه) با when(...)->needs(...)->give(...) پیادهسازی را برای هر مصرفکننده انتخاب میکند. FastAPI با انتخاب Callable ورودی Depends تصمیم میگیرد؛ Binding از Interface به پیادهسازی ندارد. چیزی که Laravel معادلش را ندارد Dependency خواننده و اعتبارسنج ورودی درخواست است که FastAPI در OpenAPI مستند میکند؛ در Laravel این کار Form Request یا Controller است. زیر PHP-FPM هر درخواست Container تازه میسازد، پس Singleton یک درخواست عمر دارد. زیر Octane تا پایان Worker زنده است؛ دقیقاً مدل Lifespan در FastAPI.
// app/Providers/AppServiceProvider.php (Laravel 13), the snippet's dependencies in container terms
public function register(): void
{
$this->app->singleton(ConnectionPool::class, fn () => new ConnectionPool(config('database.url'))); // lifespan engine
$this->app->scoped(UnitOfWork::class, fn ($app) => new UnitOfWork($app->make(ConnectionPool::class))); // SessionDep: once per request
$this->app->bind(RequestId::class, fn () => new RequestId((string) Str::uuid())); // use_cache=False: new per resolve
$this->app->when(AdminStatsController::class) // contextual binding: no FastAPI twin
->needs(NotesRepository::class)
->give(fn ($app) => new ReadReplicaNotesRepository($app->make(ConnectionPool::class)));
}
// app/Http/Controllers/NoteController.php: constructor injection + method injection
class NoteController extends Controller
{
public function __construct(private UnitOfWork $uow) {} // session: SessionDep
public function index(Request $request, Pagination $page) { /* ... */ } // page: PageDep (method injection)
}
// routes/api.php: route-group middleware is Laravel's router dependency
Route::middleware(['auth:sanctum', 'tenant'])->group(fn () => Route::get('/notes', [NoteController::class, 'index']));
// tests/Feature/NotesTest.php: swap a binding, like app.dependency_overrides
$this->app->instance(IdentityProvider::class, new FakeIdentityProvider(user: 'tester'));| Laravel / PHP | FastAPI |
|---|---|
| Service container | Container ندارد؛ گراف Dependency از امضاها |
$this->app->bind(...) | Dependency با use_cache=False، تازه در هر مصرف |
$this->app->singleton(...) | منبع Lifespan روی app.state و Dependency تحویلدهنده |
$this->app->scoped(...) | Dependency معمولی، Cache هر درخواست |
Contextual binding با when()->needs()->give() | Callable متفاوت به Depends بدهید |
| Constructor injection در Controller | پارامترهای Path operation |
Method injection و App::call(...) | هر Path operation و Dependable |
گروه Middleware در Route، auth و tenant | APIRouter(dependencies=[...]) |
| Middleware سراسری | FastAPI(dependencies=[...]) برای Route مطابق؛ Middleware برای همه |
abort(403) در Policy | raise HTTPException(403) در Dependency |
$this->app->instance(...) و $this->mock(...) | app.dependency_overrides[...] = ... |
Auth::user() بهعنوان Locator | user: CurrentUser بهصورت تزریقی |
| Singleton در Octane از درخواست فراتر میرود | منبع Lifespan برای هر Worker میان درخواستها میماند |
نگاه Go
در Go، تزریق خودکار به Handler از سوی Framework وجود ندارد؛ روش رایج، تزریق سازنده (Constructor injection) بهصورت دستی است. Handler متدی روی Struct است که فیلدهایش Dependency هستند؛ main ریشهٔ ترکیب (Composition root) است و همهچیز را یک بار میسازد و وصل میکند. همتای این فصل در Go، Mock با Interface و DI برای تستپذیری است. مقدارهای هر درخواست، مثل کاربر، Tenant و شناسه، وارد سازنده نمیشوند؛ Middleware آنها را حل و در context.Context میگذارد تا با r.Context() برسند.
دو کتابخانه سیمکشی (Wiring) اجزا را خودکار میکنند. Google Wire، "a code generation tool that automates connecting components using dependency injection" است و در آن "Dependencies between components are represented in Wire as function parameters". README اکنون با "This project is no longer maintained" شروع میشود، در حالی که بخش وضعیت پروژه هنوز میگوید "As of version v0.3.0, Wire is beta and is considered feature complete." Uber Fx، "is a dependency injection system for Go" است که زمان اجرا با fx.Provide برای سازندههایی که "are not called until they are needed" و با fx.Invoke کار میکند. Hookهای چرخهٔ عمر OnStart و OnStop نقش Lifespan را دارند؛ مستندات "Fx-managed singletons" را برای "eliminate global state" وعده میدهند. هیچکدام Cache هر درخواست یا تولید OpenAPI از سیمکشی (Wiring) اجزا ندارند. بخش درخواست در Go با Middleware و context است.
// Go: the snippet's notes API with constructor injection (the composition root is main)
type NotesStore interface {
List(ctx context.Context, tenant string, limit, offset int) ([]Note, error)
}
type NotesHandler struct { // dependencies are fields, set once (singletons)
store NotesStore
auth Authenticator
}
func NewNotesHandler(store NotesStore, auth Authenticator) *NotesHandler { // constructor injection
return &NotesHandler{store: store, auth: auth}
}
func (h *NotesHandler) List(w http.ResponseWriter, r *http.Request) {
user := UserFrom(r.Context()) // request-scoped: put there by the auth middleware (CurrentUser)
page, size, err := parsePage(r.URL.Query()) // Pagination: hand-written validation, no automatic 422
if err != nil {
http.Error(w, err.Error(), http.StatusUnprocessableEntity)
return
}
notes, err := h.store.List(r.Context(), user.Tenant, size, (page-1)*size)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
writeJSON(w, notes)
}
func main() {
db, err := sql.Open(os.Getenv("DB_DRIVER"), os.Getenv("DATABASE_URL")) // lifespan: one *sql.DB (a pool) per process
if err != nil {
log.Fatal(err)
}
defer db.Close()
h := NewNotesHandler(NewSQLNotesStore(db), NewJWTAuth(keys))
mux := http.NewServeMux()
mux.Handle("GET /notes", RequireTenantUser(h.auth, http.HandlerFunc(h.List))) // router dependency = middleware
log.Fatal(http.ListenAndServe(":8000", mux))
}
// tests: NewNotesHandler(fakeStore{}, fakeAuth{}) -- the Go form of dependency_overrides| موضوع | FastAPI | Go |
|---|---|---|
| محل اعلان Dependency | امضای Route و Dependable | فیلد Struct و پارامتر سازنده |
| Composition root | امضاها و create_app() | main() یا Wire/Fx |
| Singleton | Lifespan و app.state | یک بار ساخت در main و تحویل به پایین |
| مقدار هر درخواست | Dependency با Cache درخواست | Middleware و context.Context |
| پاکسازی | Dependency مولد و Lifespan | defer، OnStop در fx و تابع پاکسازی Wire |
| Validation ورودی | در Dependency، خودکار با 422 | دستی |
| تعویض در تست | app.dependency_overrides | تحویل پیادهسازی Fake از Interface |
| DI با تولید کد | ندارد | Wire، بدون نگهداری |
| Container زمان اجرا | ندارد | Fx با fx.Provide و fx.Invoke |
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
Depends، Singleton نگه میدارد | بین درخواستها چیزی نگه نمیدارد؛ Singleton در Lifespan است |
| Cache میان درخواستهاست | فقط برای همان درخواست |
| تابع یکسان همیشه یک مدخل Cache است | کلید شامل Scopeهای Security و scope است؛ POST /notes، get_current_user را دو بار صدا زد |
کد پس از yield پیش از پاسخ اجرا میشود | از 0.118.0 پس از پاسخ و در اجرای واقعی پس از Background task |
Commit بعد از yield امن است | شکستش 200 دریافتشدهٔ Client را عوض نمیکند |
| استثنای گرفتهشده در Dependency مولد پاسخ خوب میدهد | بدون raise، پاسخ 500 و علت گمشده؛ 0.128.8 فقط FastAPIError: Response not awaited گزارش میکند |
| Override دور اصل را میگیرد | اصل و Sub-dependencyهایش اجرا نمیشوند |
| کلاس Dependency پارامتردار را Override کنید | کلید همان نمونهٔ استفادهشده در Depends(...) است |
| Dependency سراسری برای هر درخواست اجرا میشود | فقط Route مطابق؛ نه 404/405 |
Headerهای Response تزریقی همیشه میرسند | وقتی HTTPException پاسخ را بسازد از دست میروند |
Dependency با def داخل Route با async def روی Loop است | در Thread pool اجرا میشود |
OAuth2PasswordBearer اعتبار Token را میسنجد | فقط استخراج میکند؛ نبود Header از 0.20.0 پاسخ 401 است |
from __future__ import annotations همیشه بیضرر است | در 0.128.8 کلاس را با 500 PydanticUserError و نمونهٔ Callable را با 422 خراب میکند؛ پارامتر __call__ بهصورت Query خوانده میشود |
| یک Session سراسری برای SQLite خوب است | یک شکست، تمام درخواستهای بعد را خراب میکند؛ PendingRollbackError |
max_concurrency اندازهٔ Pool را تعیین میکند | فراخوانی را برای هر شیء Depends، Event loop و Worker محدود میکند |
app.state میان همهٔ Workerها مشترک است | هر Process نسخهٔ خودش را دارد |
| DI به Container نیاز دارد | تزریق سازنده و پارامتر DI هستند؛ Container فقط سیمکشی (Wiring) را خودکار میکند |
برگهٔ تقلب
| موضوع | به یاد بسپارید |
|---|---|
| اعلان | x: Annotated[T, Depends(fn)]؛ fn را فراخوانی نکنید |
| Alias | SessionDep = Annotated[Session, Depends(get_session)] در dependencies.py |
| کلاس | Annotated[Pagination, Depends()]؛ بدون Annotationهای __future__ در همان ماژول روی 0.128.8 |
| گراف | حل Sub-dependency عمقاول؛ Route فقط گره بالا را نام میبرد |
| ترتیب | برنامه → Router → Decorator → پارامترها از چپ به راست → Route |
| Cache | یک بار در درخواست؛ کلید شامل Callable، Scopes و Scope؛ use_cache=False خواندن را رد میکند، نه نوشتن |
| Yield | try: yield x / except: rollback; raise / finally: close |
| زمان | Teardown پس از پاسخ در 0.118.0+؛ scope="function" پیش از آن در 0.121.0+ |
| Background task | شناسه بگیرد و منابع خودش را باز کند |
| Dependency اثر جانبی | dependencies=[Depends(check)] روی Decorator، APIRouter و FastAPI |
| پارامتردار | نمونهٔ Callable به نام RoleChecker("admin") در سطح ماژول؛ کارخانهٔ Closure |
| async/sync | def → Thread pool با 40 Token؛ async def → Event loop، بدون Blocking |
| Request/Response | request.app.state برای Process، request.state برای درخواست؛ Headerهای Response روی خطا گم میشوند |
| امنیت | استخراج با OAuth2PasswordBearer؛ Validation با get_current_user؛ Security(..., scopes=[...]) |
| تست | app.dependency_overrides[original] = fake؛ پاککردن پس از هر تست؛ کلید دقیقاً همان شیء |
| عمر | Engine و Client در Lifespan؛ Session و کاربر در هر درخواست؛ هرگز Session سراسری |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — FastAPI در هر درخواست با session: Annotated[Session, Depends(get_session)] چه میکند؟ حیاتی
پاسخ
پاسخ: هنگام import، get_session را Sub-dependant مربوط به Route و get_engine را Sub-dependant مربوط به get_session ثبت کرده است. در هر درخواست get_engine را با خواندن app.state.engine حل میکند؛ سپس get_session را مانند Context manager وارد میکند و چون Generator def است، Setup تا yield در Thread pool اجرا میشود. Session تحویلشده را تا پایان درخواست Cache و به Route میدهد؛ بعد از پاسخ، کد پس از yield یعنی finally: session.close() اجرا میشود. Dependency مولد.
۲ — دو Dependency به get_current_user نیاز دارند؛ چند بار اجرا میشود و چه زمانی دو بار؟ حیاتی
پاسخ
پاسخ: یک بار در درخواست، چون FastAPI مقدار را با کلید شامل Callable، Security scopes و Scope در Cache درخواست میگذارد. اگر کلید فرق کند، دو بار میشود: Security(get_current_user, scopes=["notes:write"]) و Security(..., scopes=["notes:read"]) در یک درخواست؛ اندازهگیری POST /notes دو فراخوانی نشان داد. اعلان با use_cache=False یا scope متفاوت هم میتواند اجرای دوم بدهد. هر درخواست تازه با Cache خالی شروع میشود؛ Cache.
۳ — session.commit() باید بعد از yield باشد یا داخل Route؟ چرا؟ حیاتی
پاسخ
پاسخ: در Route یا سرویسی که Route فراخوانی میکند. از 0.118.0، کد پس از yield بعد از ارسال پاسخ اجرا میشود و شکست Commit دیگر کد وضعیت را عوض نمیکند؛ Client قبلاً ۲۰۰ گرفته است، همان چیزی که test_exception_after_yield_cannot_change_a_sent_response نشان میدهد. Dependency فقط روی استثنا rollback() و پرتاب دوباره انجام دهد و در finally، close() کند. scope="function" هم Teardown را پیش از پاسخ میبرد، ولی Commit در Route روند موفقیت را صریح نگه میدارد؛ زمان Teardown.
۴ — Dependency پارامتری، Decorator، Router و سراسری چه تفاوتی دارند؟ حیاتی
پاسخ
پاسخ: مقدار Dependency پارامتری به تابع داده میشود. Dependency Decorator با @router.get(..., dependencies=[...])، در Router با APIRouter(dependencies=[...]) و سراسری با FastAPI(dependencies=[...]) برای اثر جانبی اجرا میشود و مقدارش دور ریخته میشود. تفاوت پوشش آنها بهترتیب یک Route، همهٔ Routeهای Router و همهٔ Routeهای مطابق برنامه است؛ ترتیب اجرا برنامه → Router → Decorator → پارامترهاست. هیچکدام برای Path نامنطبق با پاسخ ۴۰۴ اجرا نمیشوند؛ Router و Dependency سراسری.
۵ — جستوجوی کاربر واقعی را در تست چگونه عوض میکنید و دقیقاً چه چیزی اجرا نمیشود؟ حیاتی
پاسخ
پاسخ: با app.dependency_overrides[get_current_user] = lambda: User(...) و پاککردن دیکشنری در Fixture پس از تست. FastAPI برای هر گرهٔ هر گراف، Callable اصلی را در دیکشنری جستوجو میکند؛ جایگزین اجرا میشود و اصل و Sub-dependencyهایش، اینجا oauth2_scheme، اجرا نمیشوند، پس Header Authorization لازم نیست. پارامترهای خود Override مثل هر Dependency از درخواست خوانده میشوند؛ جایگزینی Dependency.
۶ — RoleChecker را Override کردهاید، ولی بررسی مدیر هنوز ۴۰۳ میدهد؛ چرا؟ مهم
پاسخ
پاسخ: Route از Depends(require_admin) استفاده میکند و require_admin = RoleChecker("admin") یک نمونه است. FastAPI، __call__ نمونه را اجرا میکند و خود نمونه کلید Override است؛ کلاس RoleChecker اصلاً در گراف نیست، پس dependency_overrides[RoleChecker] نادیده میماند. dependency_overrides[require_admin] را جایگزین کنید؛ اجرای واقعی با کلید کلاس ۴۰۳ و با نمونه ۲۰۴ داد. Dependency پارامتردار.
۷ — Dependency مولد، ValueError را میگیرد و دوباره پرتاب نمیکند؛ Client چه میبیند و چه چیزی Log میشود؟ مهم
پاسخ
پاسخ: پاسخ ۵۰۰ Internal Server Error و گمشدن ValueError اصلی. از 0.110.0، FastAPI مطابق رفتار معمول Python، استثنای بلعیدهشده را منتقل نمیکند. در اجرای واقعی 0.128.8، سرور فقط FastAPIError: Response not awaited... میبیند که except بدون پرتاب را علت احتمالی میداند، نه خطای اصلی را. در except یا استثنای تازه مثل HTTPException(400) پرتاب کنید تا Client آن را بگیرد، یا با raise اصل را دوباره پرتاب کنید؛ استثناها.
۸ — چه چیزی در Lifespan و چه چیزی در Dependency قرار میگیرد؟ مثال Engine و Session چیست؟ مهم
پاسخ
پاسخ: منبع سراسری Process که قابل بازاستفاده و برای Threadها امن است، مثل Engine در SQLAlchemy و Pool آن، httpx.AsyncClient، تنظیمات و مدل، در Lifespan ساخته میشود؛ یک بار در هر Worker روی app.state ذخیره یا بهصورت Lifespan state تحویل داده میشود. شیء وضعیتدار هر درخواست، مثل Session با Transaction مستقل، کاربر جاری و Tenant، در Dependency ساخته میشود. Dependency مربوط به Session، Engine را از request.app.state.engine میخواند. Session سراسری یک Transaction را میان درخواستها مشترک میکند؛ در برنامهٔ قبل یک شکست، درخواست بعدی را به PendingRollbackError رساند؛ منابع Lifespan.
۹ — کد پس از yield در FastAPI جاری چه زمانی اجرا میشود و تاریخچهاش چیست؟ مهم
پاسخ
پاسخ: پس از ارسال پاسخ؛ اجرای واقعی 0.128.8 ترتیب شروع پاسخ، سپس Background task و بعد Teardown معکوس Setup را نشان داد. پیش از 0.106.0 پس از پاسخ بود؛ 0.106.0 آن را پیش از پاسخ برد و پشتیبانی مصرف منابع yield در Background task را حذف کرد. نسخهٔ 0.118.0 دوباره آن را پس از پاسخ برد تا StreamingResponse بتواند از Session استفاده کند؛ 0.121.0، Depends(scope="function") را برای Teardown پیش از پاسخ افزود. زمان Teardown.
۱۰ — Dependency سراسری X-Request-ID را روی Response تزریقی میگذارد، اما ۴۰۱ و ۴۰۴ آن را ندارند؛ چرا و راهحل چیست؟ مهم
پاسخ
پاسخ: در ۴۰۴، Router هیچ Route مطابقی پیدا نکرده، پس Dependency اجرا نشده است. در ۴۰۱، HTTPException پرتاب شده و Exception handler پاسخ تازه ساخته؛ Headerهای Response تزریقی دور ریخته شدهاند؛ هر دو در تست قطعهکد دیده شدند. Header اجباری روی همهٔ پاسخها در Middleware قرار میگیرد؛ Dependency همچنان میتواند شناسه را برای Log روی request.state بگذارد. تزریق درخواست و پاسخ.
۱۱ — bind، singleton و scoped در Laravel چه معادلهایی در FastAPI دارند؟ تکمیلی
پاسخ
پاسخ: singleton، یعنی یک بار Resolve، معادل منبع Lifespan روی app.state است که Dependency تحویل میدهد. scoped، یعنی یک بار در چرخهٔ درخواست یا Job، معادل Dependency معمولی با Cache هر درخواست است؛ bind، یعنی نمونهٔ تازه در هر Resolve، به Depends(..., use_cache=False) نزدیک است. Contextual binding (بستن وابسته به زمینه) همتا ندارد؛ با Callable متفاوت ورودی Depends پیادهسازی را انتخاب میکنید. تعویض Binding در تست با $this->app->instance معادل app.dependency_overrides است؛ برای PHP/Laravel.
۱۲ — Go بدون Framework همین کار را چگونه انجام میدهد و wire و fx چه هستند؟ تکمیلی
پاسخ
پاسخ: با Constructor injection: Handler متد Struct است که فیلدهای Interface آن را سازنده تنظیم میکند و main گراف را یک بار وصل میکند. مقدارهای هر درخواست با context.Context میرسند و Middleware آنها را قرار میدهد. Google Wire کد سیمکشی (Wiring) را هنگام Compile تولید میکند؛ README اکنون میگوید نگهداری نمیشود. Uber Fx در زمان اجرا با fx.Provide و fx.Invoke گراف میسازد و Hookهای OnStart و OnStop دارد؛ تست، Fake را به سازنده میدهد. نگاه Go.
واژهنامه
| اصطلاح | معنا |
|---|---|
| تزریق وابستگی (Dependency injection) | کد همکاران لازم را اعلام میکند؛ بخش دیگری میسازد و تحویل میدهد |
| وارونگی کنترل (Inversion of control) | Framework کد را صدا میزند و ورودی را تعیین میکند؛ DI مثالی از این ایدهٔ کلی است |
| مکانیاب سرویس (Service locator) | Registry که کد همکاران را از آن میخواهد؛ جایگزین DI در توضیح Fowler و ضدالگو در اینجا |
| تزریق سازنده (Constructor injection) | تحویل همکاران به آرگومان __init__ یا سازنده؛ روش رایج Go |
| ریشهٔ ترکیب (Composition root) | محل واحد ساخت گراف اشیا؛ main و create_app() |
Depends() | نشانگر FastAPI: این Callable را حل و نتیجه را تزریق کن |
| فراهمکننده (Dependable) | Callable دادهشده به Depends |
| مصرفکننده (Dependant) | تابع اعلانکنندهٔ Dependency؛ Route و Dependable دارای Sub-dependency |
| Dependency قابل فراخوانی (Callable dependency) | تابع، کلاس یا نمونه با __call__ |
| Dependency کلاسی (Class dependency) | کلاس بهعنوان Dependable؛ خواندن پارامترهای __init__ از درخواست |
| نام مستعار Annotated (Annotated alias) | X = Annotated[T, Depends(fn)]؛ نوع و نشانگر قابل بازاستفاده در PEP 593 |
SessionDep | Alias متداول Session پایگاه داده برای هر درخواست |
| زیروابستگی (Sub-dependency) | Dependency یک Dependency |
| گراف وابستگی (Dependency graph) | همهٔ Dependableهای یک Path operation با حل عمقاول |
| ترتیب حل وابستگی (Dependency resolution order) | برنامه → Router → Decorator → پارامتر؛ Sub-dependency هر گره اول |
| حافظهٔ نهان وابستگی (Dependency cache) | دیکشنری مقدارهای حلشدهٔ هر درخواست، با کلید Callable، Scopes و Scope |
use_cache | گزینهٔ Depends؛ False دوباره Dependable را در همان درخواست صدا میزند |
| Dependency مولد (Yield dependency) | Dependable مولد: Setup، yield value، Teardown |
| آمادهسازی / جمعکردن منابع (Setup / teardown) | کد پیش و پس از yield |
scope | Depends(..., scope="function" or "request")؛ زمان Teardown از 0.121.0+ |
| Dependency Decorator (Decorator dependencies) | dependencies=[...] روی Decorator عملیات؛ مقدار دور ریخته میشود |
| Dependency Router (Router dependencies) | APIRouter(dependencies=[...]) برای همهٔ Routeهای Router |
| Dependency سراسری (Global dependencies) | FastAPI(dependencies=[...]) برای هر Route مطابق |
| Dependency پارامتردار (Parameterised dependency) | تنظیم با آرگومان؛ نمونهٔ کلاس Callable یا کارخانهٔ Closure |
| کارخانهٔ Closure (Closure factory) | تابعی که Dependency تازه با متغیرهای بستهشده روی آرگومانها میسازد |
| تزریق درخواست (Request injection) | اعلان request: Request برای گرفتن درخواست Starlette |
| تزریق پاسخ (Response injection) | اعلان response: Response برای Header، Cookie و وضعیت موفقیت |
app.state | مجموعهٔ Attributeهای برنامه برای هر Process در Starlette |
request.state | مجموعهٔ Attributeهای هر درخواست؛ دریافت کپی سطحی Lifespan state هم دارد |
| وضعیت چرخهٔ عمر (Lifespan state) | دیکشنری تحویلشده در yield مربوط به Lifespan که در هر request.state کپی میشود |
| چرخهٔ عمر (Lifespan) | Context manager ناهمگام دور عمر برنامه؛ Startup پیش از yield و Shutdown پس از آن |
| موتور (Engine) | شیء SQLAlchemy مالک Pool اتصال؛ یک بار برای هر Process |
| نشست (Session) | Unit of work در SQLAlchemy با یک Transaction در هر لحظه؛ یک بار برای هر درخواست |
OAuth2PasswordBearer | Dependency امنیتی استخراج Bearer token؛ نبود آن از 0.20.0 پاسخ 401 |
Security() | Depends() همراه Scopeهای OAuth2 مستند در OpenAPI |
SecurityScopes | شیء تزریقی فهرستکنندهٔ Scopeهای لازم همهٔ Dependantها |
dependency_overrides | دیکشنری app از Dependable اصلی به جایگزین |
max_concurrency | گزینهٔ Depends از 0.163.0+ برای محدودیت فراخوانی همزمان هر شیء Depends |
| مجموعهٔ Threadها (Thread pool) | Threadهای Worker در AnyIO با 40 Token برای Dependency و Route def |
AsyncExitStack | Stack کتابخانهٔ استاندارد برای ورود Dependency مولد؛ خروج آخرین ورودی اول |
| ظرف سرویس Laravel (Laravel service container) | Container مربوط به DI در Laravel با bind، singleton، scoped و Contextual binding |
| Wire / Fx | ابزار DI در Go؛ تولید کد هنگام Compile در Wire بدون نگهداری؛ Container زمان اجرا در Fx |
| Pydantic | Validation همهٔ ورودیهای Dependency و مدلهای تزریقشده |
| SQLAlchemy / SQLModel / Alembic | ORM، لایهٔ ORM با طعم Pydantic و ابزار Migration فصلهای داده |
| pytest / httpx / Uvicorn / Starlette | اجراکنندهٔ تست، Client زیر TestClient، سرور ASGI و Toolkit پایهٔ FastAPI |
منابع
- FastAPI, "Dependencies": https://fastapi.tiangolo.com/tutorial/dependencies/
- FastAPI, "Classes as Dependencies": https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/
- FastAPI, "Sub-dependencies": https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/
- FastAPI, "Dependencies in path operation decorators": https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/
- FastAPI, "Global Dependencies": https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/
- FastAPI, "Dependencies with yield": https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/
- FastAPI, "Advanced Dependencies" (parameterised,
max_concurrency, yield history): https://fastapi.tiangolo.com/advanced/advanced-dependencies/ - FastAPI, "Testing Dependencies with Overrides": https://fastapi.tiangolo.com/advanced/testing-dependencies/
- FastAPI, "Dependencies - Depends() and Security()" (reference): https://fastapi.tiangolo.com/reference/dependencies/
- FastAPI, "FastAPI class" (reference,
dependencies): https://fastapi.tiangolo.com/reference/fastapi/ - FastAPI, "APIRouter class" (reference): https://fastapi.tiangolo.com/reference/apirouter/
- FastAPI, "Bigger Applications - Multiple Files" (router dependencies, order): https://fastapi.tiangolo.com/tutorial/bigger-applications/
- FastAPI, "Security - First Steps" (
OAuth2PasswordBearer): https://fastapi.tiangolo.com/tutorial/security/first-steps/ - FastAPI, "Get Current User": https://fastapi.tiangolo.com/tutorial/security/get-current-user/
- FastAPI, "Simple OAuth2 with Password and Bearer": https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/
- FastAPI, "OAuth2 with Password (and hashing), Bearer with JWT tokens": https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/
- FastAPI, "OAuth2 scopes" (
Security,SecurityScopes): https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/ - FastAPI, "Use Old 403 Authentication Error Status Codes" (0.122.0 change): https://fastapi.tiangolo.com/how-to/authentication-error-status-code/
- FastAPI, "Lifespan Events": https://fastapi.tiangolo.com/advanced/events/
- FastAPI, "Using the Request Directly": https://fastapi.tiangolo.com/advanced/using-request-directly/
- FastAPI, "Response - Change Status Code" (Response in dependencies): https://fastapi.tiangolo.com/advanced/response-change-status-code/
- FastAPI, "Response Headers": https://fastapi.tiangolo.com/advanced/response-headers/
- FastAPI, "Background Tasks" (with dependency injection): https://fastapi.tiangolo.com/tutorial/background-tasks/
- FastAPI, "SQL (Relational) Databases" (
SessionDep): https://fastapi.tiangolo.com/tutorial/sql-databases/ - FastAPI, "Concurrency and async / await" (dependencies in the thread pool): https://fastapi.tiangolo.com/async/
- FastAPI, "Testing": https://fastapi.tiangolo.com/tutorial/testing/
- FastAPI, "Release Notes" (0.20.0, 0.95.0, 0.106.0, 0.110.0, 0.118.0, 0.121.0, 0.122.0, 0.123.0, 0.128.2, 0.137.0, 0.144.0, 0.162.x, 0.163.0): https://fastapi.tiangolo.com/release-notes/
- FastAPI source at 0.128.8 (
fastapi/dependencies/utils.py): https://github.com/fastapi/fastapi/blob/0.128.8/fastapi/dependencies/utils.py - SQLModel, "Session with FastAPI Dependency": https://sqlmodel.tiangolo.com/tutorial/fastapi/session-with-dependency/
- Starlette, "Requests" (
request.state): https://www.starlette.dev/requests/ - Starlette, "Applications" (
app.state): https://www.starlette.dev/applications/ - Starlette, "Lifespan" (lifespan state): https://www.starlette.dev/lifespan/
- Starlette, "Thread Pool" (40 tokens): https://www.starlette.dev/threadpool/
- SQLAlchemy 2.0, "Session Basics" (session per web request): https://docs.sqlalchemy.org/en/20/orm/session_basics.html
- PEP 593, "Flexible function and variable annotations": https://peps.python.org/pep-0593/
- Martin Fowler, "Inversion of Control Containers and the Dependency Injection pattern" (2004): https://martinfowler.com/articles/injection.html
- Laravel 13, "Service Container": https://laravel.com/docs/13.x/container
- Laravel 13, "Service Providers": https://laravel.com/docs/13.x/providers
- Google Wire, README: https://github.com/google/wire
- Google Wire, User Guide: https://github.com/google/wire/blob/main/docs/guide.md
- Uber Fx, documentation: https://uber-go.github.io/fx/
- Uber Fx, "Container": https://uber-go.github.io/fx/container.html
- Uber Fx, "Lifecycle": https://uber-go.github.io/fx/lifecycle.html
- PyPI, FastAPI (versions and
requires_python): https://pypi.org/project/fastapi/