خطاها و پاسخها: HTTPException، Exception handlerهای اختصاصی، Problem Details، مدل پاسخ، StreamingResponse و SSE، فایلهای ایستا
"Errors are any other exception that occurs within the application. These cases should bubble through the entire middleware stack as exceptions. Any error logging middleware should ensure that it re-raises the exception all the way up to the server." — مستندات Starlette، «Exceptions»، starlette.dev/exceptions
خلاصه (Summary): پاسخ FastAPI از دو راه ساخته میشود: عملیات مسیر (Path operation) مقداری یا شیء Response برمیگرداند، یا استثنایی (Exception) رخ میدهد. مدیریتکنندهٔ خطا (Exception handler) در سازوکار دولایهٔ Starlette اجرا میشود: ExceptionMiddleware خطاهای مدیریتشده مثل HTTPException، RequestValidationError و کلاسهای دامنه (Domain) را به پاسخ معمولی تبدیل میکند. بیرونیترین میانافزار (Middleware)، یعنی ServerErrorMiddleware، Exception handler ثبتشده برای Exception یا 500 را اجرا میکند، پاسخ 500 میفرستد و خطا را با raise دوباره (Re-raise) بالا میفرستد تا سرور آن را ثبت کند. در مورد موفقیت، مقدار خروجی با مدل پاسخ (Response model)، یعنی response_model یا اعلان نوع بازگشت (Return type annotation)، پالایش و سریالسازی (Serialisation) میشود. راه دیگر انتخاب کلاس پاسخ، مانند JSONResponse، HTMLResponse، PlainTextResponse، RedirectResponse، FileResponse یا StreamingResponse است؛ در این مورد بایتها را خودتان تعیین میکنید. پاسخ جریانی (Streaming response) با مولد (Generator) ساخته میشود: بدنه (Body) با کدگذاری انتقال قطعهای (Chunked transfer encoding) ارسال میشود، فشار برگشتی (Back-pressure) مولد را در await send متوقف میکند و قطع اتصال کارخواه (Client disconnect) آن را لغو میکند. رویدادهای ارسالی سرور (Server-Sent Events)، یا SSE، صرفاً قالببندی متنی event:، id:، retry:، data: و خط خالی روی همین جریان هستند. تمرکز (Focus): ساخت HTTPException با status_code، detail و سرآیند (Header)، تفاوت کلاس FastAPI با starlette.exceptions.HTTPException، تعریف کلاس خطای اختصاصی و ثبت آن با @app.exception_handler یا add_exception_handler؛ شناخت Exception handler مربوط به Exception، رفتار ServerErrorMiddleware، raise دوباره (Re-raise) و 500 Internal Server Error، حالت (Mode) اشکالزدایی (Debug mode) و جایگزینی Exception handler مربوط به RequestValidationError؛ استفاده از جزئیات مشکل (Problem Details) در RFC 9457 با application/problem+json، نگاشت خطاهای Domain مثل OrderNotFound به 404 Not Found و OutOfStock به 409 Conflict، ثبت خطا با شناسهٔ درخواست (Request id) و مستندسازی مدل خطا با responses؛ انتخاب بین response_model و Return type annotation، کاربرد response_model_exclude_unset و response_model_exclude_none، انتخاب response_class و کلاسهای پاسخ از جمله ORJSONResponse و orjson؛ تنظیم Header و کوکی (Cookie) با Set-Cookie روی Response، ساخت 201 Created همراه Location، پاسخ 204 No Content و 304 Not Modified و آشنایی با ETag؛ دانلود با FileResponse و مقدمهٔ بارگذاری، ساخت StreamingResponse با Generator معمولی یا ناهمگام (Async generator)، Back-pressure و request.is_disconnected؛ قالب text/event-stream، شناسه و زمان تلاش دوبارهٔ رویداد و Last-Event-ID، مقایسهٔ EventSourceResponse در sse-starlette با fastapi.sse در FastAPI 0.135، بافرکردن پراکسی (Proxy buffering)، X-Accel-Buffering و کامنتهای Keep-alive (Keep-alive comments)، جریان توکن مدل زبانی بزرگ (LLM)؛ نصب StaticFiles با html=True، سیاست Cache-Control فایلهای ایستا و زمان واگذاری آنها به شبکهٔ توزیع محتوا (CDN) یا Nginx، و آشنایی با BackgroundTasks. هدف یادگیری (Learning goal): سرویسی بسازید که وضعیت و بدنهٔ هر شکست فقط در یک جا تعیین شود، جزئیات داخلی به کارخواه نرسد، هر 500 با Request id در گزارشها پیدا شود، کلاس هر پاسخ آگاهانه انتخاب شود و جریانها در برابر کارخواه کند، قطع اتصال و پراکسی درست رفتار کنند.
این صفحه سمت پاسخ در FastAPI را پوشش میدهد: تبدیل Exception به پاسخ و ساخت پاسخهای غیر JSON یا طولانی. بدنهٔ 422، قالب اعتبارسنجی (Validation) در RFC 9457 با اشارهگر JSON (JSON Pointer) و اولین Exception handler مربوط به Problem Details در اعتبارسنجی درخواست است؛ اینجا همان نام عضوها را برای گردش 500، نگاشت Domain و Request id به کار میبریم. مبانی Route، کد وضعیت و اولین HTTPException در مبانی FastAPI آمده است. وابستگی (Dependency) با yield و زمان پاکسازی آن نسبت به ارسال جریان در تزریق وابستگی، و محل Exception handler و router در پروژهٔ بزرگ در APIRouter و ساختار پروژه بررسی میشود. شرح کامل BackgroundTasks، حافظهٔ نهان (Cache) و کارخواه HTTP خروجی در کارهای پسزمینه، Caching و APIهای خارجی است. تنظیم Uvicorn/Gunicorn، گزارشگیری (Logging) و Nginx جلوی برنامه در FastAPI در محیط عملیاتی، Endpoint جریانی LLM پروژه در پروژهٔ FastAPI AI/RAG، و سمت ارائهدهنده در APIهای LLM در عمل آمده است. طراحی وضعیت و قالب خطا در طراحی REST API، Chunked encoding و قاببندی HTTP/2 در تکامل HTTP، و مقایسهٔ polling، SSE و WebSocket در مقیاس بالا در ارتباط بلادرنگ است. همتای Go را در سرور و کارخواه net/http، خطا، panic، recover و defer و بارگذاری فایل، S3 و CDN ببینید.
مبنای اطلاعات این صفحه مستندات FastAPI دربارهٔ Handling Errors، Response Model، Response Status Code، Static Files، Background Tasks، Additional Responses، Additional Status Codes، Custom Response، Return a Response Directly، Response Headers، Response Cookies، Stream Data، Server-Sent Events، مرجع پاسخها، خطاها و StaticFiles و یادداشتهای انتشار تا 0.165.0 در ۱۸ نوامبر ۲۰۲۶ است. مستندات Starlette دربارهٔ پاسخ، خطا، Middleware، درخواست و فایل ایستا، کد نصبشدهٔ Starlette 0.49.3، FastAPI 0.128.8، Uvicorn 0.39.0 و sse-starlette 3.3.0 که کنار دیگر منابع ذخیره شدهاند، README بستهٔ sse-starlette، بخش Server-sent events استاندارد WHATWG HTML، RFC 9457، RFC 9110 و RFC 9112، مستندات ngx_http_proxy_module در Nginx، README بستهٔ orjson، مستندات خطا، پاسخ و filesystem در Laravel 13.x و نوشتهٔ «Working with Errors in Go 1.13» نیز مبنا هستند. صفحه برای Python 3.12+ و FastAPI جاری نوشته شده است. قطعهکدها روی تنها مفسر ماشین ساخت، CPython 3.9.6، اجرا شدهاند؛ بنابراین جدیدترین نسخههای قابل نصب روی آن ثابت شدهاند: FastAPI 0.128.8، Starlette 0.49.3، Pydantic 2.13.5، Uvicorn 0.39.0، sse-starlette 3.3.0، orjson 3.11.5، httpx 0.28.1 و pytest 8.4.2 بهاضافهٔ eval-type-backport. مجموعهٔ حلشده در requirements.lock ذخیره شده است. برچسب «واقعی» در ادامه به خروجی همان اجرا اشاره دارد. قابلیتهای جدیدتر با تاریخ انتشار توضیح داده شدهاند: yield همراه response_class=StreamingResponse و JSON Lines در 0.134.0، ۲۷ فوریهٔ ۲۰۲۶؛ fastapi.sse.EventSourceResponse در 0.135.0، ۱ مارس ۲۰۲۶؛ منسوخشدن ORJSONResponse در 0.131.0، ۲۲ فوریهٔ ۲۰۲۶؛ و app.frontend() در 0.138.0، ۲۰ ژوئن ۲۰۲۶.
نقشهٔ صفحه (Page map)
| اگر دنبال این هستید | بروید به |
|---|---|
| جدولهایی که در یک دقیقه میتوان حفظ کرد | همهچیز در یک دقیقه |
| چرا شکستها Exception و پاسخها کلاس هستند | چرا وجود دارد |
| تغییر نسخهها از Exception handlerهای Starlette تا SSE در FastAPI 0.135 | از کجا آمده |
| سرویس پیش و پس از اصلاح | Python |
کاربرد raise HTTPException(404, detail=..., headers=...) | HTTPException |
انتخاب کلاس HTTPException برای ثبت Exception handler | تفاوت FastAPI و Starlette |
ثبت @app.exception_handler(MyError) | [کلاسها و Exception handlerهای اختصاصی](#exception-Exception handler) |
گردش 500، ServerErrorMiddleware و raise دوباره (Re-raise) | Exception handler مربوط به Exception |
اثر FastAPI(debug=True) | Debug mode |
| تغییر بدنهٔ 422 | جایگزینی RequestValidationError |
استفادهٔ یکدست از application/problem+json | قالب مشترک Problem Details |
نگاشت OrderNotFound به 404 و OutOfStock به 409 | نگاشت خطای Domain |
| پیدا کردن 500 در گزارشها | Logging با Request id |
نمایش خطا در /docs | پارامتر responses و مدل خطا |
انتخاب response_model یا -> OrderOut | مدل پاسخ و اعلان بازگشت |
حذف null و مقدارهای پیشفرض | exclude_unset و exclude_none |
کاربرد HTMLResponse، RedirectResponse و ORJSONResponse | کلاسهای پاسخ |
اثر return JSONResponse(...) | بازگرداندن مستقیم Response |
| Header و Cookie روی پاسخ | Header پاسخ و Set-Cookie |
201 همراه Location، 204 و 304 همراه ETag | معنای کدهای وضعیت |
دانلود، Range و بارگذاری | FileResponse |
| Generator و Chunked encoding | StreamingResponse |
| کارخواه کند | Back-pressure |
| کارخواه زبانه را بسته است | قطع اتصال |
| Exception پس از اولین بایت | خطای میانهٔ جریان |
قالب text/event-stream، id: و retry: | SSE |
انتخاب sse-starlette، fastapi.sse یا پیادهسازی دستی | پیادهسازیهای SSE |
| Buffering در Nginx و مهلت بیکاری | پراکسی و Keep-alive |
| فرستادن تدریجی توکن LLM | جریان توکن |
کاربرد app.mount("/app", StaticFiles(...)) | StaticFiles |
| کار پس از پاسخ | مقدمهٔ BackgroundTasks |
| اتفاقات درونی و متن دقیق گزارشها | سازوکار |
| باگهای رایج و اصلاحشان | حل مسائل رایج |
| انتخاب کلاس پاسخ و شیوهٔ انتقال جریان | انتخاب |
| از یکپارچه تا سیستم توزیعشده | در معماری |
| بازتولید رفتار روی ماشین خودتان | آزمایشگاه |
Exception handler و response()->stream در Laravel | برای توسعهدهندهٔ PHP/Laravel |
مقدار error و errors.Is در Go | زاویهٔ Go |
همهچیز در یک دقیقه (One minute)
هر شکست کجا میرود؟ همهٔ ردیفها خروجی واقعی برنامهٔ قطعهکدها هستند و در فهرست مفاهیم باز میشوند.
| اتفاق | دریافتکنندهٔ خطا | وضعیت | بدنه در برنامهٔ قطعهکدها |
|---|---|---|---|
raise HTTPException(401, headers={"WWW-Authenticate": "Bearer"}) | ExceptionMiddleware ← Exception handler کلاس HTTPException در Starlette | 401 + Header | application/problem+json، type: about:blank |
| router هیچ Route پیدا نمیکند | همان Exception handler؛ router کلاس HTTPException در Starlette را raise میکند | 404 | Problem، title: Not Found |
| Path درست است ولی متد نیست | همان Exception handler | 405 + allow | Problem، title: Method Not Allowed |
| ورودی نامعتبر | Exception handler مربوط به RequestValidationError | 422 | Problem با عضو افزودهٔ errors |
raise OrderNotFound(...) در store | Exception handler مربوط به DomainError و جدول نگاشت | 404 | Problem، type: .../order-not-found |
raise OutOfStock(...) / DuplicateOrder(...) | همان | 409 | Problem، type: .../out-of-stock |
raise PaymentProviderDown(...) | همان | 503 + Retry-After | Problem |
| هر Exception دیگر | ServerErrorMiddleware ← Exception handler مربوط به Exception | 500 | Problem عمومی با request_id؛ سپس raise دوباره (Re-raise) و ثبت در Uvicorn |
| Exception پس از اولین بایت جریان | دیگر هیچکس نمیتواند وضعیت را عوض کند | 200 قبلاً ارسال شده | بدنهٔ Chunked ناتمام |
| هیچ Exception handler نصب نشده | پیشفرضهای Starlette | مانند بالا | JSON با {"detail": ...}؛ برای 500 متن Internal Server Error با text/plain |
انتخاب کلاس پاسخ. response_class= نوع رسانه (Media type) را مستند میکند؛ بازگرداندن Instance (نمونهٔ کلاس) آن را همانطور که ساختهاید میفرستد.
| کلاس | Media type | کاربرد | نکته |
|---|---|---|---|
| بدون کلاس؛ مدل یا نوع بازگشت | application/json | پاسخ معمولی API | سریعترین راه: Pydantic مدل را مستقیم سریالسازی میکند |
JSONResponse | application/json | JSON دستی و بدنهٔ خطا | هنگام return، response_model را دور میزند |
ORJSONResponse | application/json | افزایش سرعت در کد قدیمی | از 0.131.0 منسوخ؛ نیازمند orjson |
PlainTextResponse | text/plain; charset=utf-8 | بررسی سلامت و قطعههای CSV | |
HTMLResponse | text/html; charset=utf-8 | صفحهٔ کوچک، پیشنمایش ایمیل | قالبها: Jinja2 |
RedirectResponse | — | پیشفرض 307؛ با آرگومان 301/302/303/308 | Header با نام Location |
FileResponse | از نام فایل | دانلود | Content-Length، Last-Modified، ETag، Range ← 206 |
StreamingResponse | خودتان تعیین میکنید | خروجی، پراکسی، متن LLM و SSE دستی | Chunked؛ بدون Content-Length |
EventSourceResponse در sse-starlette یا fastapi.sse 0.135+ | text/event-stream | SSE با ping و Header آماده | دو کلاس متفاوت با نام یکسان |
Response | خودتان تعیین میکنید | 204، 304 و بایتهای ازپیشساخته | کلاس پایهٔ همهٔ موارد |
جریانها در یک جدول.
| موضوع | کار لازم | نتیجهٔ واقعی قطعهکد |
|---|---|---|
| قاببندی (Framing) | StreamingResponse(gen(), media_type=...) | transfer-encoding: chunked، بدون content-length |
| منبع مسدودکننده (Blocking)، مانند فایل یا cursor همگام DB | Generator همگام؛ Starlette آن را در Thread pool پیمایش میکند | خروجی CSV با 5000 ردیف |
| کارخواه کند | کار اضافهای لازم نیست؛ await send مولد را متوقف میکند | وقتی کارخواه چیزی نمیخواند تولید پس از 18 × 64 KiB ایستاد |
| قطع اتصال | یک await در هر قطعه؛ request.is_disconnected() بین قطعهها | ticks cancelled after 18 chunks (client disconnected) |
| Headerهای SSE | text/event-stream، Cache-Control: no-store، X-Accel-Buffering: no | دستی یا با sse-starlette |
| اتصال (Connection) بیکار | خط توضیح : keep-alive تقریباً هر 15 ثانیه | با ping=0.1 سه توضیح در 0.3 ثانیه |
| ادامهٔ جریان | id: برای هر رویداد؛ خواندن Last-Event-ID | Last-Event-ID: 1 ← فقط رویداد 2 |
چرا وجود دارد (Why it exists)
API در HTTP دو جور نتیجه دارد: چیزی که کارخواه خواسته، و دلیل اینکه نمیتواند آن را دریافت کند. در بسیاری از چارچوبها شکل دوم پراکنده است: تابعی {"error": ...} را با وضعیت 200 میدهد، تابعی tuple برمیگرداند و تابعی Exception را به صفحهٔ HTML تبدیل میکند. پاسخ Starlette که FastAPI به ارث برده این است: شکست را Exception بدان و تبدیلش به HTTP را متمرکز کن. هر جا، در Dependency یا سرویسی چند فراخوانی پایینتر، خطا را raise کنید؛ Exception handler یک بار ثبتشده آن را به پاسخ تبدیل میکند. شکست مورد انتظار، یا «handled exceptions» به تعبیر Starlette، پاسخی معمولی میشود که از همهٔ Middlewareها برمیگردد. خطای غیرمنتظره، یا «errors»، به 500 تبدیل میشود و انتشارش ادامه پیدا میکند تا سرور آن را ثبت کند. همین تفکیک در موفقیت هم هست: مقدار بازگشتی از Response model برای Validation، پالایش و مستندسازی میگذرد؛ شیء Response دقیقاً همانطور که ساخته شده ارسال میشود. HTML، فایل، تغییر مقصد (Redirect)، 204 و جریان از راه دوم ساخته میشوند.
| خطا بهشکل مقدار بازگشتی؛ برنامهٔ «پیش از اصلاح» | Exception و یک لایهٔ نگاشت؛ برنامهٔ «پس از اصلاح» |
|---|---|
return {"error": "not found"} با 200 | raise OrderNotFound(...) ← Problem با 404 |
| هر Endpoint قالب خودش را میسازد | یک پوشش application/problem+json |
| سرویس مقدار شبیه HTTP برمیگرداند | سرویس خطای Domain را raise میکند و HTTP نمیشناسد |
except Exception: return 400 باگ را پنهان میکند | باگ به 500 تبدیل و یک بار با Request id ثبت میشود |
پشتهٔ خطا یا رازها در بدنه با debug=True | بدنهٔ عمومی؛ جزئیات فقط در گزارش |
/docs فقط 200 را نشان میدهد | responses= وضعیتهای 404/409/503 را با مدل خطا مستند میکند |
تصویری از زندگی روزمره. پذیرش هتل همان لایهٔ پاسخ است. هر اتفاقی در طبقات بالا بیفتد، مهمان پاسخی روشن و مؤدبانه در قالب هتل میگیرد: «اتاق ۴۱۲ آماده نیست؛ این مدت باید منتظر بمانید.» نظافت و آشپزخانه به لابی نمیآیند؛ یادداشت کوتاهی مثل «اتاق تمیز نشده» یا «فر خراب است» بالا میفرستند. پذیرش پوشهای دارد، همان Exception handlerها، که جواب و کد هر یادداشت را مشخص میکند. یادداشتی که در پوشه نیست، مثل «آب از سقف میریزد»، به مدیر شیفت، یعنی ServerErrorMiddleware، میرسد. مدیر فقط میگوید «مشکلی داریم، این شمارهٔ پیگیری شماست» و با همان شماره گزارش حادثه مینویسد؛ همان raise دوباره (Re-raise) و گزارش سرور. رساندن غذا ظرفبهظرف به اتاق هم جریان است: وقتی میز مهمان پر باشد پیشخدمت صبر میکند، یعنی Back-pressure؛ اگر مهمان تسویه کند آشپزخانه پختن را متوقف میکند، یعنی Disconnect.
سه بدفهمی رایج، همین ابتدا (Three common misunderstandings, up front)
۱. «با ثبت Exception handler برای Exception، خطا دیگر مدیریتشده است.» فقط پاسخ 500 دست شماست. ServerErrorMiddleware بعد از ارسال باز هم خطا را raise میکند: "We always continue to raise the exception. This allows servers to log the error, or allows test clients to optionally raise the error within the test case"؛ از کد Starlette 0.49.3. به همین دلیل TestClient(app) با وجود ساختهشدن 500، RuntimeError را در تست raise میکند و Uvicorn پیام Exception in ASGI application را ثبت میکند؛ هر دو واقعیاند. ۲. «return HTTPException(...) و raise HTTPException(...) یکی هستند.» return باگ است. بدون Return annotation، خروجی {"status_code":409,"detail":"out of stock","headers":null} با وضعیت 200 است؛ با -> Any سریالسازی شکست میخورد و کارخواه 500 میگیرد؛ هر دو واقعیاند. ۳. «Streaming فقط برای فایل بزرگ است.» هر بدنهای که هنگام تولید ارسال شود جریان است: CSV، پاسخ سرویس بالادست (Upstream)، توکن LLM و هر Endpoint مربوط به SSE. در همهٔ آنها وضعیت و Header با اولین بایت ثابت میشود، کارخواه کند تولیدکننده را نگه میدارد و رفتن کارخواه آن را لغو میکند.
از کجا آمده (Where it comes from)
طراحی Exception در Starlette پیش از FastAPI وجود داشت: خطاهای مدیریتشده مثل HTTPException را ExceptionMiddleware رندر میکند و دیگر خطاها را ServerErrorMiddleware که "always the outermost middleware layer" است. FastAPI همین سازوکار را نگه داشت و زیرکلاس خودش از HTTPException را افزود؛ detail آن "any JSON-able data" را میپذیرد. RequestValidationError و Exception handlerهای پیشفرض در fastapi.exception_handlers هم اضافه شدند. سپس زمان اجرای کارهای اطراف Exception تغییر کرد: 0.106.0 در ۲۵ دسامبر ۲۰۲۳ اجازه داد Dependency دارای yield پس از yield خطا raise کند: "Before FastAPI 0.106.0, raising exceptions after yield was not possible". نسخهٔ 0.118.0 در ۲۹ سپتامبر ۲۰۲۵ کد خروج Dependency دارای yield را دوباره به پس از ارسال پاسخ برد، چون در غیر این صورت "the StreamingResponse would not be able to use that session while streaming data". در سمت پاسخ، 0.130.0 سریالسازی JSON با Pydantic در Rust را آورد؛ 0.131.0 در ۲۲ فوریهٔ ۲۰۲۶، ORJSONResponse و UJSONResponse را منسوخ کرد؛ 0.134.0 در ۲۷ فوریهٔ ۲۰۲۶، "streaming JSON Lines and binary data with yield" و 0.135.0 در ۱ مارس ۲۰۲۶، "support for Server Sent Events" یعنی fastapi.sse را افزود. FileResponse در Starlette از درخواست بازه (Range request) پشتیبانی کرد: "If the request includes a Range header, and the file exists, the response will be a 206 Partial Content response". Problem Details در سال ۲۰۱۶ به RFC 7807 و در ژوئیهٔ ۲۰۲۳ به RFC 9457 رسید که "obsoletes RFC 7807". SSE در بخش ۹٫۲ استاندارد WHATWG HTML تعریف میشود.
1 2016-03 RFC 7807 Problem Details for HTTP APIs
2 2019-02 FastAPI 0.1.x on Starlette: HTTPException + exception_handlers
3 2022-06 RFC 9110 (HTTP semantics: 201/204/304/409/422) and RFC 9112 (chunked coding)
4 2023-07 RFC 9457 obsoletes RFC 7807; FastAPI 0.100 on Pydantic v2
5 2023-12 FastAPI 0.106: dependencies with yield may raise after yield
6 2025-09 FastAPI 0.118: yield-dependency exit runs after the response (streams keep their session)
7 2026-02 0.130 Rust JSON serialisation; 0.131 ORJSONResponse deprecated; 0.134 yield streaming + JSON Lines
8 2026-03 FastAPI 0.135: fastapi.sse EventSourceResponse, ServerSentEvent
9 2026-06 FastAPI 0.138: app.frontend() for single-page apps on top of StaticFiles
10 2026-11 sse-starlette 3.7.1 (needs Python 3.11+); snippets pin 3.3.0, the last for 3.9پایتون (Python)
قبل (Before)
API سفارش در روز خلوت ظاهراً کار میکند. سفارش گمشده 200 با {"error": ...} میدهد؛ اتمام موجودی بهجای raise، HTTPException را برمیگرداند؛ ایجاد سفارش 200 و بدون Location است. except Exception کلی، باگ KeyError('sku') را 400 میکند و پیامش را لو میدهد. debug=True پشتهٔ خطا و راز داخل پیام Exception را به کارخواه میفرستد. خروجیگیری ابتدا ۱۰٬۰۰۰ ردیف را در حافظه میسازد، بعد آن را جریان مینامد و Content-Type هم ندارد. Endpoint رویدادها JSON را بدون قاببندی و Headerهای SSE ارسال میکند.
"""Before: the error and response bugs this chapter removes. Every one is pinned by tests/test_before.py."""
import asyncio
import json
from typing import Any, Dict
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse, StreamingResponse
app = FastAPI(debug=True) # 1. debug=True: a 500 sends the full traceback (with locals' source) to the client
ORDERS: Dict[int, Dict[str, Any]] = {1: {"id": 1, "sku": "BOOK-1", "qty": 1, "status": "shipped"}}
STOCK = {"BOOK-1": 5, "GAME-1": 0}
@app.get("/orders/{order_id}")
def get_order(order_id: int) -> Any:
try:
return ORDERS[order_id]
except KeyError:
return {"error": "not found"} # 2. status 200 for a failure; caches and clients believe it
@app.post("/orders")
def create_order(body: Dict[str, Any]): # type: ignore[no-untyped-def] (no return annotation)
try:
if STOCK[body["sku"]] < body["qty"]:
return HTTPException(409, "out of stock") # 3. *returned*, not raised: serialised with 200
STOCK[body["sku"]] -= body["qty"]
new_id = max(ORDERS) + 1
ORDERS[new_id] = {"id": new_id, **body, "status": "open"}
return ORDERS[new_id] # 4. 200 instead of 201, no Location header
except Exception as exc: # 5. catch-all turns bugs into 400s and leaks the message
return JSONResponse({"error": str(exc)}, status_code=400)
@app.get("/boom")
def boom() -> Any:
raise RuntimeError("database password is hunter2")
@app.get("/export")
def export() -> StreamingResponse:
rows = [json.dumps({"id": i}) + "\n" for i in range(10_000)] # 6. whole export built in memory first
return StreamingResponse(iter(rows)) # 7. no media_type: no Content-Type header at all
@app.get("/events")
async def events() -> StreamingResponse:
async def gen(): # type: ignore[no-untyped-def]
for i in range(3):
yield json.dumps({"n": i}) # 8. not SSE framing: no "data:" and no blank line
await asyncio.sleep(0)
# 9. text/plain, no Cache-Control: no-store, no X-Accel-Buffering: no, no keep-alive comments
return StreamingResponse(gen())تستها هر باگ را جداگانه ثبت میکنند؛ همه واقعیاند:
"""Pins down every bug in app/before.py."""
from fastapi.testclient import TestClient
from app.before import app
client = TestClient(app, raise_server_exceptions=False)
def test_missing_order_is_a_200() -> None:
r = client.get("/orders/99")
assert r.status_code == 200 and r.json() == {"error": "not found"}
def test_returned_http_exception_is_serialised_with_200() -> None:
r = client.post("/orders", json={"sku": "GAME-1", "qty": 1})
assert r.status_code == 200
assert r.json() == {"status_code": 409, "detail": "out of stock", "headers": None}
def test_create_answers_200_without_location() -> None:
r = client.post("/orders", json={"sku": "BOOK-1", "qty": 1})
assert r.status_code == 200 and "location" not in r.headers
def test_catch_all_turns_a_bug_into_400_and_leaks_the_message() -> None:
r = client.post("/orders", json={"qty": 1}) # KeyError('sku') is a bug, reported as a client error
assert r.status_code == 400 and r.json() == {"error": "'sku'"}
def test_debug_true_sends_the_traceback_to_the_client() -> None:
r = client.get("/boom")
assert r.status_code == 500
assert r.headers["content-type"].startswith("text/plain") # non-browser client: plain traceback
assert "hunter2" in r.text and "Traceback" in r.text
def test_streaming_without_media_type_has_no_content_type() -> None:
r = client.get("/export")
assert "content-type" not in r.headers
assert r.text.count("\n") == 10_000
def test_events_are_not_sse() -> None:
r = client.get("/events")
assert "content-type" not in r.headers
assert r.text == '{"n": 0}{"n": 1}{"n": 2}' # no data: lines, no blank-line separatorsبعد (After)
لایهٔ Domain معنای شکست را raise میکند و کاری با HTTP ندارد:
"""Domain errors: raised by the service layer, which knows nothing about HTTP.
The HTTP layer (app/problems.py) maps each class to a status code and a Problem Details type.
Compare Go's sentinel errors + errors.Is and Laravel's report()/render() on the exception.
"""
from typing import Any, Dict
class DomainError(Exception):
"""Base class: one handler for this class covers every subclass (handler lookup walks the MRO)."""
def __init__(self, detail: str, **context: Any) -> None:
super().__init__(detail)
self.detail = detail
# Safe, client-facing context (ids, counts). Never secrets or raw input.
self.context: Dict[str, Any] = context
class OrderNotFound(DomainError):
"""No order with that id (or not visible to this caller)."""
class OutOfStock(DomainError):
"""The request is valid, but the current stock cannot satisfy it."""
class DuplicateOrder(DomainError):
"""The idempotency key was already used: the UNIQUE constraint said so."""
class OrderNotCancellable(DomainError):
"""The order's state forbids the transition (shipped orders cannot be cancelled)."""
class PaymentProviderDown(DomainError):
"""A dependency is unavailable; the client may retry later."""
def __init__(self, detail: str, retry_after: int = 30, **context: Any) -> None:
super().__init__(detail, **context)
self.retry_after = retry_afterstore نتیجهٔ SQL را به خطای Domain تبدیل میکند: rowcount == 0 به OutOfStock و IntegrityError روی کلید UNIQUE به DuplicateOrder میرسد:
"""A small SQLite store. The SQL is what the page's ```sql block shows.
sqlite3 is a blocking driver, so the routes that call it are `def` (FastAPI runs them in the thread pool).
The same mapping applies to SQLAlchemy: IntegrityError -> DuplicateOrder, NoResultFound -> OrderNotFound.
"""
import sqlite3
import threading
from typing import Any, Dict, Optional
from app.domain import DuplicateOrder, OrderNotCancellable, OrderNotFound, OutOfStock
SCHEMA = """
CREATE TABLE stock (
sku TEXT PRIMARY KEY,
available INTEGER NOT NULL CHECK (available >= 0)
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
sku TEXT NOT NULL REFERENCES stock (sku),
qty INTEGER NOT NULL CHECK (qty > 0),
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'shipped', 'cancelled')),
note TEXT,
idempotency_key TEXT UNIQUE
);
"""
RESERVE_SQL = "UPDATE stock SET available = available - ? WHERE sku = ? AND available >= ?"
INSERT_SQL = "INSERT INTO orders (sku, qty, note, idempotency_key) VALUES (?, ?, ?, ?)"
GET_SQL = "SELECT id, sku, qty, status, note FROM orders WHERE id = ?"
CANCEL_SQL = "UPDATE orders SET status = 'cancelled' WHERE id = ? AND status = 'open'"
class Store:
def __init__(self) -> None:
self._conn = sqlite3.connect(":memory:", check_same_thread=False)
self._conn.row_factory = sqlite3.Row
self._lock = threading.Lock()
self._conn.executescript(SCHEMA)
self._conn.executemany(
"INSERT INTO stock (sku, available) VALUES (?, ?)", [("BOOK-1", 5), ("GAME-1", 0)]
)
self._conn.execute("INSERT INTO orders (sku, qty, status) VALUES ('BOOK-1', 1, 'shipped')")
self._conn.commit()
def get(self, order_id: int) -> Dict[str, Any]:
row = self._conn.execute(GET_SQL, (order_id,)).fetchone()
if row is None:
raise OrderNotFound(f"Order {order_id} does not exist.", order_id=order_id)
return dict(row)
def create(self, sku: str, qty: int, note: Optional[str], key: Optional[str]) -> Dict[str, Any]:
with self._lock, self._conn: # one transaction: reserve stock, insert order
if self._conn.execute(RESERVE_SQL, (qty, sku, qty)).rowcount == 0:
available = self._conn.execute(
"SELECT available FROM stock WHERE sku = ?", (sku,)
).fetchone()
raise OutOfStock(
f"{sku}: {available[0] if available else 0} left, {qty} requested.",
sku=sku,
requested=qty,
)
try:
cur = self._conn.execute(INSERT_SQL, (sku, qty, note, key))
except sqlite3.IntegrityError as exc: # UNIQUE(idempotency_key); the with-block rolls back
raise DuplicateOrder("This Idempotency-Key was already used.") from exc
return self.get(cur.lastrowid)
def cancel(self, order_id: int) -> None:
with self._lock, self._conn:
if self._conn.execute(CANCEL_SQL, (order_id,)).rowcount == 1:
return
status = self.get(order_id)["status"] # raises OrderNotFound when missing
raise OrderNotCancellable(f"Order {order_id} is {status}.", order_id=order_id, state=status)یک ماژول مسئول HTTP خطاهاست: جدول نگاشت، مدل Problem و چهار Exception handler:
"""The HTTP side of errors: one mapping table, Problem Details bodies, and every handler.
Same member names as the Request Validation chapter's Problem model (type, title, status, detail,
instance + extensions); this module adds request_id and the domain mapping.
"""
import logging
from http import HTTPStatus
from typing import Any, Dict, Optional, Tuple, Type
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from fastapi.utils import is_body_allowed_for_status_code
from pydantic import BaseModel
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.domain import (
DomainError,
DuplicateOrder,
OrderNotCancellable,
OrderNotFound,
OutOfStock,
PaymentProviderDown,
)
from app.observability import request_id_var
log = logging.getLogger("shop")
PROBLEM_JSON = "application/problem+json"
TYPE_BASE = "https://shop.example/problems/"
# The domain error mapping: the only place that knows which domain failure is which HTTP status.
DOMAIN_STATUS: Dict[Type[DomainError], Tuple[int, str, str]] = {
OrderNotFound: (404, "order-not-found", "Order not found"),
OutOfStock: (409, "out-of-stock", "Not enough stock"),
DuplicateOrder: (409, "duplicate-order", "Duplicate order"),
OrderNotCancellable: (409, "order-not-cancellable", "Order cannot be cancelled"),
PaymentProviderDown: (503, "payment-provider-down", "Payment provider unavailable"),
}
class Problem(BaseModel):
"""Error response model (RFC 9457), used in `responses=` so OpenAPI documents the errors."""
type: str = "about:blank"
title: str
status: int
detail: Optional[str] = None
instance: Optional[str] = None
request_id: Optional[str] = None
PROBLEM_RESPONSES: Dict[Any, Dict[str, Any]] = {
code: {
"model": Problem,
"description": desc,
"content": {PROBLEM_JSON: {"schema": {"$ref": "#/components/schemas/Problem"}}},
}
for code, desc in [(404, "Not found"), (409, "Conflict"), (503, "Dependency unavailable")]
}
def problem(request: Request, status: int, title: str, *, type_: str = "about:blank",
detail: Optional[str] = None, headers: Optional[Dict[str, str]] = None,
**extensions: Any) -> JSONResponse:
body: Dict[str, Any] = {"type": type_, "title": title, "status": status,
"instance": request.url.path, "request_id": request_id_var.get()}
if detail is not None:
body["detail"] = detail
body.update(extensions)
return JSONResponse(body, status_code=status, headers=headers, media_type=PROBLEM_JSON)
async def domain_error_handler(request: Request, exc: DomainError) -> JSONResponse:
# Walk the MRO so a subclass of OutOfStock still maps to 409.
for cls in type(exc).__mro__:
if cls in DOMAIN_STATUS:
status, slug, title = DOMAIN_STATUS[cls] # type: ignore[index]
break
else: # an unmapped DomainError is a bug in the mapping, not a client error
log.error("unmapped domain error %s", type(exc).__name__)
status, slug, title = 500, "unmapped-domain-error", "Internal Server Error"
headers = {"Retry-After": str(exc.retry_after)} if isinstance(exc, PaymentProviderDown) else None
log.info("domain error %s -> %s", type(exc).__name__, status)
return problem(request, status, title, type_=TYPE_BASE + slug, detail=exc.detail,
headers=headers, **exc.context)
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> Response:
# Registered for Starlette's class: catches router 404/405 too, not only our raise HTTPException.
detail = exc.detail if isinstance(exc.detail, str) else None
extra = {} if isinstance(exc.detail, str) else {"errors": exc.detail}
title = HTTPStatus(exc.status_code).phrase
if not is_body_allowed_for_status_code(exc.status_code): # 1xx, 204, 304: headers only
return Response(status_code=exc.status_code, headers=exc.headers)
return problem(request, exc.status_code, title, detail=detail,
headers=dict(exc.headers) if exc.headers else None, **extra)
async def validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
# Minimal: the full RFC 9457 validation format (pointers, per-field codes) lives in the
# Request Validation chapter. Never echo `input`; it may hold passwords or personal data.
errors = [{"loc": list(e["loc"]), "code": e["type"], "detail": e["msg"]} for e in exc.errors()]
return problem(request, 422, "Unprocessable Content", type_=TYPE_BASE + "validation",
detail=f"{len(errors)} validation error(s)", errors=errors)
async def unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
# Runs inside ServerErrorMiddleware, which re-raises afterwards so Uvicorn logs the traceback
# too. Log once here with the request id; return nothing internal to the client.
log.exception("unhandled %s on %s %s", type(exc).__name__, request.method, request.url.path)
rid = request_id_var.get()
return problem(request, 500, "Internal Server Error", detail="Unexpected error. Quote the request id.",
headers={"X-Request-ID": rid})
def install_problem_handlers(app: FastAPI) -> None:
app.add_exception_handler(DomainError, domain_error_handler)
app.add_exception_handler(StarletteHTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_handler)
app.add_exception_handler(Exception, unhandled_handler) # key Exception (or 500) -> ServerErrorMiddlewareRequest id، پالایهٔ گزارش و Middleware خالص ASGI:
"""Request ids for logs and error bodies.
A pure ASGI middleware (not BaseHTTPMiddleware, which is awkward with streaming responses) stores the id
in a ContextVar and adds X-Request-ID to every response that passes through it. The 500 response built
by ServerErrorMiddleware does NOT pass through it (that middleware is outside every user middleware),
so the 500 handler reads the ContextVar and sets the header itself.
"""
import logging
import uuid
from contextvars import ContextVar
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
request_id_var: ContextVar[str] = ContextVar("request_id", default="-")
class RequestIdFilter(logging.Filter):
"""Copies the current request id onto every log record as %(request_id)s."""
def filter(self, record: logging.LogRecord) -> bool:
record.request_id = request_id_var.get()
return True
def configure_logging() -> logging.Logger:
logger = logging.getLogger("shop")
if not logger.handlers:
logger.addFilter(RequestIdFilter()) # on the logger: every record from "shop" gets the id
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(levelname)s [%(request_id)s] %(name)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
class RequestIdMiddleware:
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
incoming = dict(scope["headers"]).get(b"x-request-id", b"").decode("latin-1")
rid = incoming if 0 < len(incoming) <= 64 else uuid.uuid4().hex
# Not reset on exit on purpose: the 500 handler runs after this middleware has unwound
# and still needs the id. Each request runs in its own task, so values do not leak across requests.
request_id_var.set(rid)
async def send_with_id(message: Message) -> None:
if message["type"] == "http.response.start":
MutableHeaders(scope=message)["X-Request-ID"] = rid
await send(message)
await self.app(scope, receive, send_with_id)برنامه مدل پاسخ و اعلان بازگشت، 201 همراه Location، 204، یک Route برای ETag/304، همهٔ کلاسهای پاسخ، Cookie، responses= برای خطاها و نصب StaticFiles با html=True و Cache-Control مستقل هر فایل را نشان میدهد:
"""After: errors raised as exceptions and mapped once, every response class used on purpose."""
from __future__ import annotations
import hashlib
import json
import logging
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Annotated, Any, AsyncIterator, Dict
from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Path as PathParam, Request, Response, status
from fastapi.responses import (
FileResponse,
HTMLResponse,
JSONResponse,
ORJSONResponse,
PlainTextResponse,
RedirectResponse,
)
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from app.db import Store
from app.domain import PaymentProviderDown
from app.observability import RequestIdMiddleware, configure_logging
from app.problems import PROBLEM_RESPONSES, install_problem_handlers
from app.streaming import router as streaming_router
log = configure_logging()
HERE = Path(__file__).parent
class OrderIn(BaseModel):
sku: str = Field(min_length=1, max_length=32)
qty: int = Field(gt=0, le=10)
note: str | None = None
class OrderOut(BaseModel):
id: int
sku: str
qty: int
status: str
note: str | None = None
class Preferences(BaseModel):
language: str = "en"
newsletter: bool = False
timezone: str | None = None
class CachedStaticFiles(StaticFiles):
"""StaticFiles sets ETag and Last-Modified but no Cache-Control; add one per file kind."""
def file_response(self, *args: Any, **kwargs: Any) -> Response:
response = super().file_response(*args, **kwargs)
path = str(args[0]) if args else ""
if "/assets/" in path: # fingerprinted names (app.3f9a1c.css) never change: cache for a year
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
else: # index.html and friends: revalidate every time (the ETag makes that a cheap 304)
response.headers["Cache-Control"] = "no-cache"
return response
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
app.state.store = Store()
app.state.prefs = {"u1": {"language": "fa"}} # only one field ever set by the user
yield
app = FastAPI(title="Orders with errors done right", version="1.0.0", lifespan=lifespan)
install_problem_handlers(app)
app.add_middleware(RequestIdMiddleware)
app.include_router(streaming_router)
def store(request: Request) -> Store:
return request.app.state.store
def send_confirmation(order_id: int) -> None:
log.info("confirmation sent for order %s", order_id) # BackgroundTasks preview: runs after the response
@app.get("/orders/{order_id}", response_model=OrderOut, response_model_exclude_none=True,
responses={404: PROBLEM_RESPONSES[404]}, tags=["orders"])
def get_order(order_id: Annotated[int, PathParam(ge=1)], request: Request) -> Dict[str, Any]:
order = store(request).get(order_id) # raises OrderNotFound -> 404 Problem via the handler
order["internal_cost_cents"] = 412 # filtered out by response_model, never sent
return order
@app.post("/orders", status_code=status.HTTP_201_CREATED, responses={409: PROBLEM_RESPONSES[409]},
tags=["orders"])
def create_order(body: OrderIn, request: Request, response: Response, tasks: BackgroundTasks,
idempotency_key: Annotated[str | None, Header()] = None) -> OrderOut:
order = store(request).create(body.sku, body.qty, body.note, idempotency_key)
response.headers["Location"] = f"/orders/{order['id']}" # 201 Created + Location header
tasks.add_task(send_confirmation, order["id"])
return OrderOut(**order) # the return type annotation is the response model here
@app.delete("/orders/{order_id}", status_code=status.HTTP_204_NO_CONTENT,
responses={404: PROBLEM_RESPONSES[404], 409: PROBLEM_RESPONSES[409]}, tags=["orders"])
def cancel_order(order_id: int, request: Request) -> None:
store(request).cancel(order_id) # 204 No Content: FastAPI sends no body
@app.get("/orders/{order_id}/receipt", tags=["orders"])
def receipt(order_id: int, request: Request,
if_none_match: Annotated[str | None, Header()] = None) -> Response:
order = store(request).get(order_id)
body = json.dumps(order, sort_keys=True).encode()
etag = '"' + hashlib.sha256(body).hexdigest()[:16] + '"' # ETag preview: strong validator of the bytes
headers = {"ETag": etag, "Cache-Control": "private, no-cache"}
if if_none_match == etag:
return Response(status_code=status.HTTP_304_NOT_MODIFIED, headers=headers) # no body
return Response(body, media_type="application/json", headers=headers)
@app.get("/legacy/orders/{order_id}", include_in_schema=False)
def legacy_order(order_id: int) -> RedirectResponse:
return RedirectResponse(f"/orders/{order_id}", status_code=status.HTTP_308_PERMANENT_REDIRECT)
@app.get("/fast/orders/{order_id}", response_class=ORJSONResponse, tags=["responses"])
def fast_order(order_id: int, request: Request) -> ORJSONResponse:
# Deprecated in FastAPI 0.131.0: a response model is serialised in Rust and is as fast.
return ORJSONResponse(store(request).get(order_id))
@app.get("/health", response_class=PlainTextResponse, include_in_schema=False)
def health() -> str:
return "ok"
@app.get("/welcome", response_class=HTMLResponse, tags=["responses"])
def welcome() -> str:
return "<!doctype html><title>Shop</title><h1>Welcome</h1>"
@app.get("/invoices/{order_id}.pdf", response_class=FileResponse, tags=["responses"])
def invoice(order_id: int, request: Request) -> FileResponse:
store(request).get(order_id) # 404 Problem first if the order is unknown
return FileResponse(HERE / "files" / "invoice.pdf", media_type="application/pdf",
filename=f"invoice-{order_id}.pdf") # Content-Disposition: attachment
@app.post("/session", tags=["responses"])
def login(response: Response) -> Dict[str, str]:
response.set_cookie("session", "opaque-token", httponly=True, secure=True, samesite="lax", max_age=3600)
return {"status": "signed in"} # Set-Cookie on Response: merged into the final JSON response
@app.get("/users/{user_id}/preferences", response_model=Preferences,
response_model_exclude_unset=True, tags=["responses"])
def preferences(user_id: str, request: Request) -> Preferences:
# Only fields that were explicitly set are sent; defaults stay out of the payload.
return Preferences(**request.app.state.prefs.get(user_id, {}))
@app.get("/me", tags=["errors"])
def me(authorization: Annotated[str | None, Header()] = None) -> Dict[str, str]:
if not authorization:
raise HTTPException(status_code=401, detail="Missing bearer token.",
headers={"WWW-Authenticate": "Bearer"}) # headers on exceptions
return {"user": "u1"}
@app.post("/payments", tags=["errors"], responses={503: PROBLEM_RESPONSES[503]})
def pay() -> Dict[str, str]:
raise PaymentProviderDown("The card processor timed out.", retry_after=30)
@app.get("/boom", include_in_schema=False)
def boom() -> Dict[str, str]:
raise RuntimeError("database password is hunter2") # must never reach the client
@app.get("/manual-404", tags=["errors"])
def manual_404() -> JSONResponse:
# Returning a Response skips response_model and the exception handlers: you own everything.
return JSONResponse({"detail": "hand-made"}, status_code=404)
# A mount owns every path under its prefix; html=True serves index.html for "/app/".
app.mount("/app", CachedStaticFiles(directory=HERE / "static", html=True), name="static")Streaming و SSE شامل خروجی CSV با Generator همگام، Async generator آگاه از Disconnect، آزمون Back-pressure، SSE دستی با id و retry و Keep-alive comments و Last-Event-ID، همان جریان با sse-starlette و جریان توکن شبیه LLM است:
"""StreamingResponse and Server-Sent Events on FastAPI 0.128.8 (no fastapi.sse yet: that is 0.135.0+)."""
import asyncio
import csv
import io
import json
import logging
from typing import Annotated, Any, AsyncIterator, Dict, Iterator, List, Optional
from fastapi import APIRouter, Header, Query, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from sse_starlette import EventSourceResponse, ServerSentEvent
log = logging.getLogger("shop")
router = APIRouter(tags=["streaming"])
# What the generators did, so tests (and the lab) can see cleanup after a disconnect.
STREAM_EVENTS: List[str] = []
PRODUCED: Dict[str, int] = {"chunks": 0}
SSE_HEADERS = {
"Cache-Control": "no-store", # never store an event stream (no-cache would allow storage + revalidation)
"X-Accel-Buffering": "no", # Nginx: pass bytes through as they arrive
}
# ---------- StreamingResponse ----------
def csv_rows(count: int) -> Iterator[str]:
"""A sync generator: Starlette iterates it in the thread pool (iterate_in_threadpool)."""
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(["id", "sku", "qty"])
for i in range(1, count + 1):
writer.writerow([i, f"SKU-{i % 7}", i % 3 + 1])
if buf.tell() > 8192: # flush in ~8 KiB pieces, not one write per row
yield buf.getvalue()
buf.seek(0)
buf.truncate()
yield buf.getvalue()
@router.get("/export/orders.csv")
def export_csv(rows: Annotated[int, Query(ge=1, le=1_000_000)] = 1000) -> StreamingResponse:
return StreamingResponse(csv_rows(rows), media_type="text/csv",
headers={"Content-Disposition": 'attachment; filename="orders.csv"'})
@router.get("/stream/ticks")
async def ticks(request: Request, n: Annotated[int, Query(ge=1, le=10_000)] = 5,
delay: Annotated[float, Query(ge=0, le=5)] = 0.0) -> StreamingResponse:
async def gen() -> AsyncIterator[bytes]:
sent = 0
try:
for i in range(n):
if await request.is_disconnected(): # cheap check between chunks
STREAM_EVENTS.append(f"ticks: client gone after {sent}")
return
yield f"tick {i}\n".encode()
sent += 1
await asyncio.sleep(delay) # an await: also the point where cancellation lands
STREAM_EVENTS.append(f"ticks: done {sent}")
except asyncio.CancelledError:
STREAM_EVENTS.append(f"ticks: cancelled after {sent}")
log.info("ticks cancelled after %s chunks (client disconnected)", sent)
raise
finally:
STREAM_EVENTS.append("ticks: cleanup") # close upstream calls, cursors, files here
return StreamingResponse(gen(), media_type="text/plain")
@router.get("/stream/big")
async def big(chunks: Annotated[int, Query(ge=1, le=100_000)] = 64,
size: Annotated[int, Query(ge=1, le=1_048_576)] = 65536) -> StreamingResponse:
"""For the back-pressure lab: counts how far the producer gets ahead of a slow reader."""
PRODUCED["chunks"] = 0
payload = b"x" * size
async def gen() -> AsyncIterator[bytes]:
for _ in range(chunks):
PRODUCED["chunks"] += 1
yield payload # `await send(...)` behind this yield blocks while the socket buffer is full
return StreamingResponse(gen(), media_type="application/octet-stream")
# ---------- Server-Sent Events, hand-rolled ----------
def sse_frame(data: str, event: Optional[str] = None, id: Optional[str] = None,
retry: Optional[int] = None) -> bytes:
"""One SSE event: field lines, then a blank line. Multi-line data becomes several data: lines."""
lines = []
if event:
lines.append(f"event: {event}")
if id is not None:
lines.append(f"id: {id}")
if retry is not None:
lines.append(f"retry: {retry}")
lines.extend(f"data: {part}" for part in data.split("\n"))
return ("\n".join(lines) + "\n\n").encode()
ORDER_EVENTS = [
{"id": 1, "status": "paid"},
{"id": 1, "status": "packed"},
{"id": 1, "status": "shipped"},
]
@router.get("/sse/orders")
async def order_events(request: Request,
last_event_id: Annotated[Optional[str], Header()] = None,
# idle: seconds of silence after the last event (up to 5 min, for proxy-timeout labs)
idle: Annotated[float, Query(ge=0, le=300)] = 0.0,
# ping: keep-alive interval in seconds; 0 disables keep-alive comments
ping: Annotated[float, Query(ge=0, le=30)] = 15.0) -> StreamingResponse:
start = int(last_event_id) + 1 if last_event_id and last_event_id.isdigit() else 0
async def gen() -> AsyncIterator[bytes]:
yield b": stream opened\n\n" # a comment line: ignored by EventSource
yield b"retry: 5000\n\n" # reconnection time for EventSource, in ms
for seq in range(start, len(ORDER_EVENTS)):
if await request.is_disconnected():
return
yield sse_frame(json.dumps(ORDER_EVENTS[seq]), event="order", id=str(seq))
# Quiet period: keep-alive comments so proxies do not close an idle connection.
if ping == 0:
await asyncio.sleep(idle) # silent: a proxy with a shorter read timeout closes the stream
else:
waited = 0.0
while waited < idle:
step = min(ping, idle - waited)
await asyncio.sleep(step)
waited += step
yield b": keep-alive\n\n"
yield sse_frame("bye", event="end")
return StreamingResponse(gen(), media_type="text/event-stream", headers=SSE_HEADERS)
# ---------- Server-Sent Events with sse-starlette ----------
@router.get("/sse/lib")
async def lib_events(request: Request) -> EventSourceResponse:
async def gen() -> AsyncIterator[Any]:
for seq, item in enumerate(ORDER_EVENTS):
yield ServerSentEvent(data=json.dumps(item), event="order", id=str(seq))
yield {"event": "end", "data": "bye"} # dicts work too
return EventSourceResponse(gen(), ping=15) # sets Cache-Control, X-Accel-Buffering, pings
# ---------- LLM token streaming (provider-neutral fake) ----------
class ChatIn(BaseModel):
prompt: str
async def fake_llm_tokens(prompt: str) -> AsyncIterator[str]:
"""Stands in for an OpenAI-compatible or native SDK stream (`async for chunk in stream`)."""
try:
for word in f"You asked: {prompt}. Here is a short answer.".split(" "):
await asyncio.sleep(0.01)
yield word + " "
finally:
STREAM_EVENTS.append("llm: upstream closed") # with a real SDK: close the HTTP stream
@router.post("/chat/stream")
async def chat_stream(body: ChatIn, request: Request) -> StreamingResponse:
async def gen() -> AsyncIterator[bytes]:
tokens = fake_llm_tokens(body.prompt)
try:
async for token in tokens:
if await request.is_disconnected():
STREAM_EVENTS.append("llm: client gone, stop paying for tokens")
break
yield sse_frame(json.dumps({"delta": token}), event="token")
else:
yield sse_frame("[DONE]") # sentinel the OpenAI-style clients look for
except Exception: # headers are already sent: a status code cannot change any more
log.exception("stream failed mid-way")
yield sse_frame(json.dumps({"title": "stream failed"}), event="error")
finally:
await tokens.aclose()
return StreamingResponse(gen(), media_type="text/event-stream", headers=SSE_HEADERS)برنامهٔ کوچک جداگانه برای شکست میانهٔ جریان: Generator پس از اولین قطعه خطا میدهد و Exception handler مربوط به Exception هرگز اجرا نمیشود:
"""Lab 5: an exception after the first streamed chunk. Run: uvicorn app.midstream:app --port 18922"""
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, StreamingResponse
app = FastAPI()
@app.exception_handler(Exception)
async def any_error(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse({"never": "sent"}, status_code=500) # cannot run: the response already started
@app.get("/s")
async def s() -> StreamingResponse:
async def gen(): # type: ignore[no-untyped-def]
yield b"part 1\n"
raise RuntimeError("upstream died") # status 200 and headers are already on the wire
return StreamingResponse(gen(), media_type="text/plain")تستها Exception handlerها و گردش 500، کلاس پاسخ و وضعیت، فایل ایستا، قاببندی جریان با TestClient و رفتارهایی را پوشش میدهند که فقط Uvicorn واقعی نشان میدهد: Chunked encoding، Disconnect، Back-pressure و گزارش خطای خود سرور:
from typing import Iterator
import pytest
from fastapi.testclient import TestClient
from app.main import app
from app.streaming import STREAM_EVENTS
@pytest.fixture
def client() -> Iterator[TestClient]:
# `with` runs the lifespan: a fresh Store (and fresh stock) for every test.
with TestClient(app, raise_server_exceptions=False) as c:
yield c
@pytest.fixture(autouse=True)
def clear_stream_events() -> None:
STREAM_EVENTS.clear()"""Exception handlers: domain mapping, Starlette's HTTPException, 422, 500, request ids."""
import logging
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.domain import DomainError, OutOfStock
from app.main import app
from app.observability import RequestIdMiddleware
from app.problems import install_problem_handlers
PROBLEM = "application/problem+json"
def test_domain_error_maps_to_404_problem(client: TestClient) -> None:
r = client.get("/orders/99")
assert r.status_code == 404 and r.headers["content-type"] == PROBLEM
body = r.json()
assert body["type"] == "https://shop.example/problems/order-not-found"
assert body["title"] == "Order not found" and body["status"] == 404
assert body["instance"] == "/orders/99" and body["order_id"] == 99
assert body["request_id"] == r.headers["x-request-id"]
def test_router_404_and_405_reach_the_starlette_handler(client: TestClient) -> None:
r = client.get("/no-such-route")
assert r.status_code == 404 and r.headers["content-type"] == PROBLEM
assert r.json()["type"] == "about:blank" and r.json()["title"] == "Not Found"
r = client.put("/orders/1")
assert r.status_code == 405 and r.json()["title"] == "Method Not Allowed"
assert r.headers["allow"] == "GET" # headers on exceptions survive the custom handler
def test_http_exception_headers_are_kept(client: TestClient) -> None:
r = client.get("/me")
assert r.status_code == 401 and r.headers["www-authenticate"] == "Bearer"
assert r.json()["detail"] == "Missing bearer token."
def test_retry_after_on_503(client: TestClient) -> None:
r = client.post("/payments")
assert r.status_code == 503 and r.headers["retry-after"] == "30"
def test_out_of_stock_is_409_with_extensions(client: TestClient) -> None:
r = client.post("/orders", json={"sku": "GAME-1", "qty": 1})
assert r.status_code == 409
assert r.json()["sku"] == "GAME-1" and r.json()["requested"] == 1
def test_duplicate_idempotency_key_is_409_and_rolls_back(client: TestClient) -> None:
h = {"Idempotency-Key": "k-1"}
assert client.post("/orders", json={"sku": "BOOK-1", "qty": 2}, headers=h).status_code == 201
r = client.post("/orders", json={"sku": "BOOK-1", "qty": 3}, headers=h)
assert r.status_code == 409 and r.json()["title"] == "Duplicate order"
# 5 - 2 = 3 left: the second reservation was rolled back with the failed INSERT
assert client.post("/orders", json={"sku": "BOOK-1", "qty": 3}).status_code == 201
def test_cancel_shipped_order_is_409(client: TestClient) -> None:
r = client.delete("/orders/1")
assert r.status_code == 409 and r.json()["state"] == "shipped"
assert client.delete("/orders/42").status_code == 404
def test_validation_error_is_a_problem_without_input(client: TestClient) -> None:
r = client.post("/orders", json={"sku": "", "qty": 99, "password": "secret"})
assert r.status_code == 422 and r.headers["content-type"] == PROBLEM
codes = sorted(e["code"] for e in r.json()["errors"])
assert codes == ["less_than_equal", "string_too_short"]
assert "secret" not in r.text and "input" not in r.text
def test_unhandled_error_is_a_generic_500_with_request_id(client: TestClient,
caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level(logging.ERROR, logger="shop"):
r = client.get("/boom", headers={"X-Request-ID": "req-123"})
assert r.status_code == 500 and r.headers["content-type"] == PROBLEM
assert "hunter2" not in r.text and r.json()["request_id"] == "req-123"
assert r.headers["x-request-id"] == "req-123" # set by the handler, not by the middleware
rec = next(x for x in caplog.records if x.getMessage().startswith("unhandled RuntimeError"))
assert rec.request_id == "req-123" and rec.exc_info is not None # traceback logged once, with the id
def test_server_error_middleware_re_raises() -> None:
# The handler's response was produced, and the exception still propagates to the server/test client.
with TestClient(app) as strict: # raise_server_exceptions=True (the default)
with pytest.raises(RuntimeError, match="hunter2"):
strict.get("/boom")
def _mini_app() -> FastAPI:
mini = FastAPI()
install_problem_handlers(mini)
mini.add_middleware(RequestIdMiddleware)
return mini
def test_handler_lookup_walks_the_mro() -> None:
class FlashSaleSoldOut(OutOfStock):
pass
class Unmapped(DomainError):
pass
mini = _mini_app()
@mini.get("/sold-out")
def sold_out() -> None:
raise FlashSaleSoldOut("Gone in 3 seconds.")
@mini.get("/unmapped")
def unmapped() -> None:
raise Unmapped("nobody mapped me")
c = TestClient(mini, raise_server_exceptions=False)
assert c.get("/sold-out").status_code == 409 # handled by the DomainError handler, OutOfStock entry
assert c.get("/unmapped").json()["type"].endswith("/unmapped-domain-error")
def test_a_bug_inside_a_handler_becomes_a_500() -> None:
mini = _mini_app()
class Broken(Exception):
pass
@mini.exception_handler(Broken)
async def broken_handler(request, exc): # type: ignore[no-untyped-def]
raise TypeError("handler bug")
@mini.get("/x")
def x() -> None:
raise Broken()
r = TestClient(mini, raise_server_exceptions=False).get("/x")
assert r.status_code == 500 and r.json()["title"] == "Internal Server Error"
def test_without_handlers_a_500_is_plain_text() -> None:
bare = FastAPI()
@bare.get("/boom")
def boom() -> None:
raise RuntimeError("x")
r = TestClient(bare, raise_server_exceptions=False).get("/boom")
assert r.status_code == 500 and r.text == "Internal Server Error"
assert r.headers["content-type"].startswith("text/plain")"""Response models, status codes, response classes, headers and cookies."""
import logging
import pytest
from fastapi.testclient import TestClient
def test_201_with_location_and_background_task(client: TestClient, caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level(logging.INFO, logger="shop"):
r = client.post("/orders", json={"sku": "BOOK-1", "qty": 1, "note": "gift"})
assert r.status_code == 201 and r.headers["location"] == f"/orders/{r.json()['id']}"
assert any("confirmation sent" in m for m in caplog.messages) # ran after the response
def test_response_model_filters_and_excludes_none(client: TestClient) -> None:
body = client.get("/orders/1").json()
assert "internal_cost_cents" not in body # filtered by response_model
assert "note" not in body # response_model_exclude_none=True (note is NULL)
def test_return_annotation_is_the_model(client: TestClient) -> None:
body = client.post("/orders", json={"sku": "BOOK-1", "qty": 1}).json()
assert body["note"] is None # no exclude_none on this route: null is sent
def test_exclude_unset_sends_only_what_was_set(client: TestClient) -> None:
assert client.get("/users/u1/preferences").json() == {"language": "fa"}
assert client.get("/users/u2/preferences").json() == {}
def test_204_has_no_body(client: TestClient) -> None:
order_id = client.post("/orders", json={"sku": "BOOK-1", "qty": 1}).json()["id"]
r = client.delete(f"/orders/{order_id}")
assert r.status_code == 204 and r.content == b""
# Real on 0.128.8: no body and no Content-Length, but a stray "content-type: application/json".
assert "content-length" not in r.headers
assert r.headers["content-type"] == "application/json" # the stray header, pinned as a regression check
def test_etag_and_304(client: TestClient) -> None:
first = client.get("/orders/1/receipt")
etag = first.headers["etag"]
second = client.get("/orders/1/receipt", headers={"If-None-Match": etag})
assert second.status_code == 304 and second.content == b"" and second.headers["etag"] == etag
def test_redirect_html_text_orjson(client: TestClient) -> None:
r = client.get("/legacy/orders/1", follow_redirects=False)
assert r.status_code == 308 and r.headers["location"] == "/orders/1"
assert client.get("/welcome").headers["content-type"] == "text/html; charset=utf-8"
assert client.get("/health").text == "ok"
r = client.get("/fast/orders/1")
assert r.headers["content-type"] == "application/json" and r.json()["note"] is None
def test_file_response_download_and_range(client: TestClient) -> None:
r = client.get("/invoices/1.pdf")
assert r.status_code == 200 and r.headers["content-type"] == "application/pdf"
assert r.headers["content-disposition"] == 'attachment; filename="invoice-1.pdf"'
assert {"etag", "last-modified", "content-length", "accept-ranges"} <= set(r.headers)
part = client.get("/invoices/1.pdf", headers={"Range": "bytes=0-7"})
assert part.status_code == 206 and part.content == b"%PDF-1.4"
assert client.get("/invoices/99.pdf").status_code == 404
def test_set_cookie_on_response(client: TestClient) -> None:
r = client.post("/session")
cookie = r.headers["set-cookie"]
for attr in ("session=opaque-token", "HttpOnly", "Max-Age=3600", "SameSite=lax", "Secure"):
assert attr in cookie
assert r.json() == {"status": "signed in"}
def test_returning_a_response_bypasses_handlers(client: TestClient) -> None:
r = client.get("/manual-404")
assert r.status_code == 404 and r.headers["content-type"] == "application/json"
assert r.json() == {"detail": "hand-made"} # not a Problem: no handler ran
def test_openapi_documents_error_models(client: TestClient) -> None:
spec = client.get("/openapi.json").json()
get_order = spec["paths"]["/orders/{order_id}"]["get"]["responses"]
assert set(get_order) == {"200", "404", "422"}
assert "application/problem+json" in get_order["404"]["content"]
assert "Problem" in spec["components"]["schemas"]
assert "/boom" not in spec["paths"]
assert "text/html" in spec["paths"]["/welcome"]["get"]["responses"]["200"]["content"]"""StaticFiles mount: html=True, validators, Cache-Control per file kind."""
from fastapi.testclient import TestClient
def test_html_mode_serves_index_and_404_page(client: TestClient) -> None:
r = client.get("/app/")
assert r.status_code == 200 and "Shop front end" in r.text
assert r.headers["cache-control"] == "no-cache"
missing = client.get("/app/nope.html")
assert missing.status_code == 404 and "Page not found" in missing.text # 404.html in HTML mode
def test_fingerprinted_assets_are_immutable(client: TestClient) -> None:
r = client.get("/app/assets/app.3f9a1c.css")
assert r.headers["cache-control"] == "public, max-age=31536000, immutable"
assert r.headers["content-type"] == "text/css; charset=utf-8"
def test_conditional_get_returns_304(client: TestClient) -> None:
etag = client.get("/app/").headers["etag"]
r = client.get("/app/", headers={"If-None-Match": etag})
assert r.status_code == 304 and r.content == b""
def test_only_get_and_head(client: TestClient) -> None:
assert client.head("/app/").status_code == 200
assert client.post("/app/").status_code == 405
def test_path_traversal_is_refused(client: TestClient) -> None:
assert client.get("/app/../main.py").status_code == 404
assert client.get("/app/%2e%2e/main.py").status_code == 404"""A tiny SSE parser that follows the WHATWG line rules (enough for tests)."""
from typing import Dict, List
def parse_sse(text: str) -> List[Dict[str, str]]:
events: List[Dict[str, str]] = []
current: Dict[str, str] = {}
data: List[str] = []
for line in text.replace("\r\n", "\n").split("\n"):
if line == "": # blank line: dispatch
if data or current:
if data:
current["data"] = "\n".join(data)
events.append(current)
current, data = {}, []
elif line.startswith(":"): # comment
current.setdefault("comments", "")
current["comments"] += line[1:].strip() + ";"
else:
field, _, value = line.partition(":")
value = value[1:] if value.startswith(" ") else value
if field == "data":
data.append(value)
else:
current[field] = value
return events"""StreamingResponse and SSE framing under TestClient (finite streams only: TestClient reads to the end)."""
import json
from fastapi.testclient import TestClient
from app.streaming import STREAM_EVENTS, sse_frame
from tests.sse import parse_sse
def test_csv_export_streams_with_attachment_header(client: TestClient) -> None:
r = client.get("/export/orders.csv", params={"rows": 5000})
assert r.headers["content-type"] == "text/csv; charset=utf-8"
assert r.headers["content-disposition"] == 'attachment; filename="orders.csv"'
assert "content-length" not in r.headers # length unknown up front
assert r.text.splitlines()[0] == "id,sku,qty" and len(r.text.splitlines()) == 5001
def test_async_generator_runs_cleanup(client: TestClient) -> None:
with client.stream("GET", "/stream/ticks", params={"n": 3}) as r:
lines = list(r.iter_lines())
assert lines == ["tick 0", "tick 1", "tick 2"]
assert STREAM_EVENTS == ["ticks: done 3", "ticks: cleanup"]
def test_sse_frame_format() -> None:
assert sse_frame("a\nb", event="note", id="7") == b"event: note\nid: 7\ndata: a\ndata: b\n\n"
def test_hand_rolled_sse_headers_and_events(client: TestClient) -> None:
r = client.get("/sse/orders")
assert r.headers["content-type"] == "text/event-stream; charset=utf-8"
assert r.headers["cache-control"] == "no-store" and r.headers["x-accel-buffering"] == "no"
events = parse_sse(r.text)
assert events[0] == {"comments": "stream opened;"} and events[1] == {"retry": "5000"}
orders = [e for e in events if e.get("event") == "order"]
assert [e["id"] for e in orders] == ["0", "1", "2"]
assert json.loads(orders[-1]["data"]) == {"id": 1, "status": "shipped"}
assert events[-1] == {"event": "end", "data": "bye"}
def test_last_event_id_resumes(client: TestClient) -> None:
r = client.get("/sse/orders", headers={"Last-Event-ID": "1"})
ids = [e["id"] for e in parse_sse(r.text) if e.get("event") == "order"]
assert ids == ["2"]
def test_keep_alive_comments_while_idle(client: TestClient) -> None:
r = client.get("/sse/orders", params={"idle": 0.3, "ping": 0.1})
assert r.text.count(": keep-alive\n\n") == 3
def test_ping_zero_means_silence(client: TestClient) -> None:
r = client.get("/sse/orders", params={"idle": 0.2, "ping": 0})
assert ": keep-alive" not in r.text and parse_sse(r.text)[-1] == {"event": "end", "data": "bye"}
assert client.get("/sse/orders", params={"idle": 301}).status_code == 422 # bound kept
def test_error_after_first_chunk_is_not_handled() -> None:
import pytest
from app.midstream import app as mid
with pytest.raises(RuntimeError, match="upstream died"):
TestClient(mid).get("/s") # the 500 handler cannot replace a started response
r = TestClient(mid, raise_server_exceptions=False).get("/s")
assert r.status_code == 200 and "never" not in r.text
def test_sse_starlette_headers_and_framing(client: TestClient) -> None:
r = client.get("/sse/lib")
assert r.headers["content-type"] == "text/event-stream; charset=utf-8"
assert r.headers["cache-control"] == "no-store" and r.headers["x-accel-buffering"] == "no"
assert "\r\n" in r.text # sse-starlette's default separator is CRLF
events = parse_sse(r.text)
assert [e.get("id") for e in events] == ["0", "1", "2", None]
def test_llm_token_stream_ends_with_done(client: TestClient) -> None:
r = client.post("/chat/stream", json={"prompt": "hi"})
events = parse_sse(r.text)
text = "".join(json.loads(e["data"])["delta"] for e in events if e.get("event") == "token")
assert text.startswith("You asked: hi.") and events[-1] == {"data": "[DONE]"}
assert "llm: upstream closed" in STREAM_EVENTS"""Behaviour that only a real server shows: chunked encoding, disconnects, back-pressure, server logs.
Uvicorn runs in a background thread of the test process, so the app's STREAM_EVENTS/PRODUCED globals
are visible here. Numbers printed with `pytest -s` are machine-specific; the assertions are loose.
"""
import logging
import socket
import threading
import time
from typing import Iterator, List
import httpx
import pytest
import uvicorn
from app.main import app
from app.streaming import PRODUCED, STREAM_EVENTS
def _free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return int(s.getsockname()[1])
@pytest.fixture(scope="module")
def base_url() -> Iterator[str]:
port = _free_port()
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="info"))
thread = threading.Thread(target=server.run, daemon=True)
thread.start()
while not server.started:
time.sleep(0.01)
yield f"http://127.0.0.1:{port}"
server.should_exit = True
thread.join(timeout=5)
def _wait_for(predicate, timeout: float = 3.0) -> bool: # type: ignore[no-untyped-def]
end = time.monotonic() + timeout
while time.monotonic() < end:
if predicate():
return True
time.sleep(0.02)
return False
def test_streaming_uses_chunked_transfer_encoding(base_url: str) -> None:
r = httpx.get(f"{base_url}/stream/ticks", params={"n": 3})
assert r.headers["transfer-encoding"] == "chunked" and "content-length" not in r.headers
assert r.text == "tick 0\ntick 1\ntick 2\n"
plain = httpx.get(f"{base_url}/orders/1")
assert "content-length" in plain.headers and "transfer-encoding" not in plain.headers
def test_client_disconnect_stops_the_generator(base_url: str) -> None:
with httpx.stream("GET", f"{base_url}/stream/ticks", params={"n": 10_000, "delay": 0.01}) as r:
got = [line for _, line in zip(range(3), r.iter_lines())]
assert got == ["tick 0", "tick 1", "tick 2"]
assert _wait_for(lambda: "ticks: cleanup" in STREAM_EVENTS)
print("\nafter disconnect:", STREAM_EVENTS)
assert any(e.startswith(("ticks: cancelled after", "ticks: client gone after")) for e in STREAM_EVENTS)
assert not any(e.startswith("ticks: done") for e in STREAM_EVENTS)
def test_back_pressure_pauses_the_producer(base_url: str) -> None:
chunks, size = 512, 65536 # 32 MiB in total
host, port = base_url.replace("http://", "").split(":")
sock = socket.create_connection((host, int(port)))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384)
sock.sendall(f"GET /stream/big?chunks={chunks}&size={size} HTTP/1.1\r\nHost: x\r\n\r\n".encode())
time.sleep(0.5) # a slow client: read nothing for half a second
produced_while_stalled = PRODUCED["chunks"]
received = 0
while True:
data = sock.recv(1 << 20)
if not data:
break
received += len(data)
if received >= chunks * size:
break
sock.close()
print(f"\nproduced while the client read nothing: {produced_while_stalled}/{chunks} chunks "
f"({produced_while_stalled * size // 1024} KiB); total received {received // 1024} KiB")
assert produced_while_stalled < chunks # the generator waited on `await send(...)`
assert received >= chunks * size
class _Collect(logging.Handler):
def __init__(self) -> None:
super().__init__()
self.messages: List[str] = []
def emit(self, record: logging.LogRecord) -> None:
self.messages.append(record.getMessage())
def test_uvicorn_logs_the_re_raised_exception(base_url: str) -> None:
# Uvicorn's own loggers do not propagate to the root logger, so attach a handler directly.
collect = _Collect()
logging.getLogger("uvicorn.error").addHandler(collect)
try:
r = httpx.get(f"{base_url}/boom", headers={"X-Request-ID": "live-1"})
assert r.status_code == 500 and r.json()["request_id"] == "live-1"
assert _wait_for(lambda: any("Exception in ASGI application" in m for m in collect.messages))
finally:
logging.getLogger("uvicorn.error").removeHandler(collect)[project]
name = "exception-handling-responses"
version = "0.1.0"
description = "Snippets for the Exceptions & Responses chapter: HTTPException, exception handlers, domain errors, Problem Details, response classes, StreamingResponse, SSE, StaticFiles"
# 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+ move to the latest releases (FastAPI 0.135+
# also ships fastapi.sse.EventSourceResponse, see the page).
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",
"uvicorn[standard]==0.39.0",
# Third-party SSE response class; 3.3.0 is the last release that admits Python 3.9.
"sse-starlette==3.3.0",
# Only for the ORJSONResponse demo; 3.11.5 is the last release that admits Python 3.9.
"orjson==3.11.5",
# 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 = ["."]
# Uvicorn 0.39 imports the legacy websockets API; not this project's concern.
filterwarnings = ["ignore::DeprecationWarning:websockets.*", "ignore::DeprecationWarning:uvicorn.*"]زاویهٔ Python (The Python angle)
سه قابلیت Python زیربنای این فصلاند. Exception در قابهای فراخوانی منتشر میشود؛ بنابراین raise OrderNotFound در Store.get بقیهٔ Route را کنار میگذارد و به اولین گیرندهٔ خطا میرسد. جدول Exception handler با سلسلهمراتب کلاس، یعنی type(exc).__mro__، تطبیق داده میشود؛ یک Exception handler روی کلاس پایه همهٔ زیرکلاسها را پوشش میدهد. Generator و Async generator بدنهٔ جریان را میسازند. yield یک قطعه به Starlette میدهد؛ Async generator در همان yield معلق میماند تا await send(...) منتظر سوکت باشد. هنگام لغو وظیفه (Task)، در await بعدی CancelledError دریافت میکند و بلوک finally: منابع Upstream را میبندد. Generator همگام با iterate_in_threadpool در استخر نخ (Thread pool) پیش میرود؛ خواندن Blocking در آن حلقهٔ رویداد (Event loop) را متوقف نمیکند. contextvars.ContextVar برای هر درخواست مقدار مستقلی فراهم میکند: "Context variables are natively supported in asyncio". به این ترتیب Request id بدون عبور دستی از همهٔ فراخوانیها به رکورد گزارش و Exception handler مربوط به 500 میرسد. در FastAPI 0.128.8 از from __future__ import annotations در ماژولهای دارای Dependency کلاسی پرهیز کنید؛ این دام شناختهشده در فصل Dependency آمده است. قطعهکد فقط در main.py که چنین Dependency ندارد از آن استفاده میکند.
فهرست مفاهیم (The concept catalogue)
HTTPException: پارامترهای status_code، detail و Header خطا حیاتی
به زبان ساده: raise HTTPException(status_code=404, detail="Order not found") در هر عمقی درخواست را همانجا متوقف میکند؛ کارخواه همان وضعیت و {"detail": "Order not found"} را میگیرد. اگر وضعیت به سرآیند (Header) نیاز دارد، headers= را بدهید؛ مثل WWW-Authenticate برای 401 یا Retry-After برای 429/503.
بدفهمی رایج: «میتوانم آن را return کنم.» مستندات میگویند: "Because it's a Python exception, you don't return it, you raise it." مقدار بازگشتی فقط یک شیء است: 200 با ویژگیهایش در JSON؛ نتیجهٔ واقعی test_returned_http_exception_is_serialised_with_200. با اعلان -> Any پاسخ 500 میشود؛ ثبتشده در runs/probe1-output.txt. بدفهمی دوم این است که detail باید رشته باشد. کلاس HTTPException در FastAPI مقدار JSONپذیر را قبول میکند: "any value that can be converted to JSON as the parameter detail, not only str"؛ نتیجهٔ واقعی {"detail":{"code":"out-of-stock","sku":"A"}} است. کلاس خود Starlette فقط رشته میپذیرد.
تعریف: امضا HTTPException(status_code, detail=None, headers=None) است. اگر detail ندهید Starlette از "the standard phrase for the status code" استفاده میکند؛ در اجرا HTTPException(418) به {"detail":"I'm a Teapot"} رسید. Exception handler پیشفرض FastAPI، {"detail": exc.detail} را بهشکل JSON همراه exc.headers میفرستد؛ برای وضعیتهای بدون بدنه مثل 204، 304 و 1xx بدنه ارسال نمیکند. FastAPI 0.128.7 نوع headers را از dict به Mapping تغییر داد.
GET /me (no Authorization header) (real, snippet app)
1 route me(): authorization is None
2 raise HTTPException(401, "Missing bearer token.", headers={"WWW-Authenticate": "Bearer"})
3 ExceptionMiddleware: handler for StarletteHTTPException (MRO: fastapi.HTTPException -> starlette HTTPException)
4 http_exception_handler -> problem(401, "Unauthorized", headers=exc.headers)
5 401 www-authenticate: Bearer content-type: application/problem+json
{"type":"about:blank","title":"Unauthorized","status":401,"instance":"/me","detail":"Missing bearer token.", ...}سناریوی واقعی: Dependency احراز هویت (Authentication) با 401 و WWW-Authenticate: Bearer؛ نبود حوزهٔ مجوز (Scope) با 403؛ تابع جستوجوی مشترک چند Route با 404؛ Dependency محدودسازی نرخ با 429 و Retry-After؛ بررسی اندازهٔ بارگذاری با 413.
| خواسته | بنویسید | خروجی Exception handler پیشفرض برای کارخواه |
|---|---|---|
| پیدا نشد | raise HTTPException(404, "Order not found") | 404 {"detail":"Order not found"} |
| جزئیات ساختیافته | HTTPException(409, detail={"code": "out-of-stock"}) | 409 {"detail":{"code":"out-of-stock"}} |
| چالش احراز هویت | headers={"WWW-Authenticate": "Bearer"} | 401 + Header |
| درخواست صبر | HTTPException(429, headers={"Retry-After": "30"}) | 429 + Header |
| عبارت استاندارد | HTTPException(418) | {"detail":"I'm a Teapot"} |
| بدون بدنه | HTTPException(304) | فقط Header |
اصلاح / روش استفاده: برای نتیجهٔ صرفاً HTTP، مثل احراز هویت، متد و اندازه، HTTPException را raise کنید. شکست کسبوکار باید کلاس Domain خودش را داشته باشد و یک بار نگاشت شود؛ نگاشت خطای Domain. Exception را هرگز return نکنید.
تفاوت HTTPException در FastAPI و starlette.exceptions.HTTPException حیاتی
به زبان ساده: دو کلاس HTTPException داریم؛ کلاس FastAPI زیرکلاس Starlette است. در کد خودتان کلاس FastAPI را raise کنید، ولی Exception handler را برای کلاس Starlette ثبت کنید تا 404 و 405 خود router و 404 مربوط به StaticFiles را هم بگیرد.
بدفهمی رایج: «@app.exception_handler(HTTPException) با import از fastapi همهٔ 404ها را تغییر میدهد.» فقط خطاهایی را تغییر میدهد که خودتان raise میکنید. در آزمایش واقعی runs/probe1-output.txt، Exception handler روی fastapi.HTTPException برای raise HTTPException(404) بدنهٔ {"custom": true} داد، اما Path ناشناخته همچنان {"detail":"Not Found"} برگرداند.
تعریف: مستندات رابطه را چنین توضیح میدهند: "FastAPI's HTTPException error class inherits from Starlette's HTTPException error class. The only difference is that FastAPI's HTTPException accepts any JSON-able data for the detail field, while Starlette's HTTPException only accepts strings for it. … when you register an exception handler, you should register it for Starlette's HTTPException." از from starlette.exceptions import HTTPException as StarletteHTTPException استفاده کنید.
handler registered for raise HTTPException (fastapi) router 404 / 405 StaticFiles 404
1 fastapi.HTTPException your handler default handler default handler
2 starlette.exceptions.HTTPException your handler (subclass) your handler your handlerسناریوی واقعی: API باید همهٔ 404ها، حتی غلط املایی URL، را با Problem Details بدهد؛ پاسخ 405 باید allow را حفظ کند، و در اجرا allow: GET از Exception handler اختصاصی عبور کرد؛ یا StaticFiles بدون 404.html نصب شده است.
| ایجادکنندهٔ خطا | کلاس | Exception handler کلاس Starlette آن را میگیرد؟ |
|---|---|---|
raise HTTPException(...) از fastapi | fastapi.HTTPException | بله، زیرکلاس است |
| router بدون Route | starlette.exceptions.HTTPException(404) | بله |
| متد نادرست در router | starlette.exceptions.HTTPException(405, headers={"Allow": ...}) | بله |
نبود فایل در StaticFiles بدون 404.html | کلاس Starlette | بله |
| افزونهٔ Starlette | کلاس Starlette | بله |
اصلاح / روش استفاده: یک Exception handler روی StarletteHTTPException، همان http_exception_handler قطعهکد، ثبت کنید که exc.headers را نگه دارد و قالب مشترک را بسازد. اگر فقط Logging میخواهید و بدنه باید پیشفرض بماند، در Exception handler خودتان fastapi.exception_handlers.http_exception_handler را فراخوانی کنید؛ بخش "Reuse FastAPI's exception handlers".
کلاس خطای اختصاصی، @app.exception_handler و add_exception_handler حیاتی
به زبان ساده: کلاس خطای خودتان، مانند class OutOfStock(DomainError)، را تعریف و همانجایی که مشکل پیدا میشود raise کنید. سپس تابع تبدیل به پاسخ را ثبت کنید: @app.exception_handler(DomainError) بالای async def handler(request, exc)، یا app.add_exception_handler(DomainError, handler) در تابع ثبت؛ مثل install_problem_handlers(app) در قطعهکد.
بدفهمی رایج: «هر کلاس Exception handler جدا میخواهد.» تطبیق کلاس در ترتیب حل متد (MRO) انجام میشود؛ Exception handler پایه زیرکلاسها را هم میگیرد. در test_handler_lookup_walks_the_mro، کلاس FlashSaleSoldOut(OutOfStock) به 409 رسید. بدفهمی دوم: «کد Exception handler امن است.» اگر خودش Exception بدهد، خطای جدید وارد گردش 500 میشود؛ در اجرا TypeError داخل Exception handler به 500 و پیام "During handling of the above exception, another exception occurred" رسید.
تعریف: مستندات میگویند: "You can add custom exception handlers with the same exception utilities from Starlette." Exception handler تابع همگام یا ناهمگام با قرارداد (Request, Exception) -> Response است. کلید میتواند کلاس Exception یا عدد کد وضعیت باشد؛ Exception handler با کلید 404 در اجرا 404 router را گرفت. build_middleware_stack در FastAPI 0.128.8 جدول را تقسیم میکند: کلیدهای 500 و Exception به ServerErrorMiddleware و بقیه به ExceptionMiddleware میروند.
POST /orders {"sku":"GAME-1","qty":1} (real)
1 create_order -> Store.create: UPDATE stock ... WHERE available >= 1 -> rowcount 0
2 raise OutOfStock("GAME-1: 0 left, 1 requested.", sku="GAME-1", requested=1)
3 ExceptionMiddleware: lookup type(exc).__mro__ = OutOfStock, DomainError, Exception, ...
4 DomainError -> domain_error_handler -> DOMAIN_STATUS[OutOfStock] = (409, "out-of-stock", "Not enough stock")
5 409 application/problem+json {"type":".../out-of-stock","title":"Not enough stock","status":409, ...,"sku":"GAME-1","requested":1}
6 response flows back out through RequestIdMiddleware (x-request-id added)سناریوی واقعی: اتمام موجودی، اعتبار ناکافی یا صندلی اشغالشده؛ خطای SDK پرداخت مثل CardDeclined که باید به 402/422 برسد؛ ValueError عمیق کتابخانه برای ورودی شناختهشده که نباید بیدلیل 500 شود؛ یک Exception handler برای هر بافت محدود (Bounded context) در برنامهٔ یکپارچهٔ ماژولار.
| روش ثبت | اثر |
|---|---|
@app.exception_handler(MyError) | شکل دکوراتور، هنگام import |
app.add_exception_handler(MyError, fn) | همان جدول؛ قابل فراخوانی از تابع تنظیم |
FastAPI(exception_handlers={MyError: fn}) | همان جدول؛ هنگام ساخت |
کلید عددی 404 | تطبیق HTTPException با همان وضعیت |
کلید Exception یا 500 | انتقال Exception handler به ServerErrorMiddleware و گردش 500 |
APIRouter | exception_handler ندارد؛ Exception handlerها متعلق به کل app هستند |
اصلاح / روش استفاده: برای هر Domain سلسلهمراتب کوچکی بسازید، برای هر کلاس پایه یک Exception handler ثبت کنید، ثبت را در یک تابع فراخواندهشده از کارخانهٔ برنامه (App factory) انجام دهید و برای هر ردیف نگاشت یک زیرکلاس را تست کنید.
Exception handler مربوط به Exception: ServerErrorMiddleware، raise دوباره (Re-raise) و 500 Internal Server Error حیاتی
به زبان ساده: خطایی که هیچ Exception handler دیگری نمیگیرد به 500 میرسد. با ثبت Exception handler برای Exception بدنهٔ 500 را شما میسازید؛ بدون آن کارخواه متن سادهٔ Internal Server Error میگیرد. در هر دو مورد بعد از پاسخ، Exception با raise دوباره (Re-raise) بالا میرود تا سرور آن را ثبت کند و تست بتواند ببیند.
بدفهمی رایج: «Exception handler من خطا را بلعید.» ServerErrorMiddleware با raise exc تمام میشود؛ کد Starlette 0.49.3 ذخیره شده است. در اجرای واقعی TestClient(app) بعد از ساختهشدن پاسخ، RuntimeError: database password is hunter2 را raise کرد و Uvicorn پیام ERROR: Exception in ASGI application را با پشتهٔ خطا (Traceback) ثبت کرد. بدفهمی دوم: «Middleware، Headerها را به 500 اضافه میکند.» ServerErrorMiddleware بیرون همهٔ Middlewareهای کاربر است و 500 را با send اصلی میفرستد. Header اضافهشده با @app.middleware("http") در آزمایش runs/probe1-output.txt روی 500 نبود؛ به همین دلیل Exception handler مربوط به 500 در قطعهکد خودش X-Request-ID را میگذارد.
تعریف: Starlette میگوید: "Errors are any other exception that occurs within the application. These cases should bubble through the entire middleware stack as exceptions." همچنین: "In practical terms, the error handled used is exception_handler[500] or exception_handler[Exception]." شرح ServerErrorMiddleware چنین است: "Ensures that application exceptions may return a custom 500 page, or display an application traceback in DEBUG mode. This is always the outermost middleware layer." اگر ارسال پاسخ، مثلاً جریان، شروع شده باشد، دیگر نمیتواند 500 بفرستد و فقط raise دوباره (Re-raise) میکند.
GET /boom X-Request-ID: lab-500 (real, Uvicorn 0.39.0 + curl)
1 route boom(): raise RuntimeError("database password is hunter2")
2 ExceptionMiddleware: no handler for RuntimeError -> re-raise
3 RequestIdMiddleware: sees the exception pass (cannot touch the response)
4 ServerErrorMiddleware: handler = unhandled_handler -> log.exception(...) -> Problem 500 + X-Request-ID
5 send 500 via the outer send; then `raise exc`
6 Uvicorn: INFO "GET /boom HTTP/1.1" 500 Internal Server Error
7 Uvicorn: ERROR Exception in ASGI application + traceback
client: {"type":"about:blank","title":"Internal Server Error","status":500,"instance":"/boom","request_id":"lab-500",
"detail":"Unexpected error. Quote the request id."}سناریوی واقعی: تیکت پشتیبانی با Request id که مهندس کشیک در گزارشها جستوجو میکند؛ ابزار ردیابی خطا مثل Sentry یا OpenTelemetry در لایهٔ بیرونی که به raise دوباره (Re-raise) متکی است؛ مجموعهتستی که Exception اصلی را با raise_server_exceptions=True، مقدار پیشفرض، میخواهد و تست دیگری که با False بدنهٔ 500 را بررسی میکند.
| تنظیم | دریافتی کارخواه | ثبتکنندهٔ گزارش |
|---|---|---|
بدون Exception handler، debug=False | 500 با Internal Server Error و text/plain | Uvicorn بهدلیل raise دوباره (Re-raise) |
Exception handler برای Exception | بدنهٔ شما؛ در قطعهکد Problem عمومی و request_id | Exception handler شما و Uvicorn |
debug=True | Traceback؛ برای مرورگر HTML و در غیر آن متن | Uvicorn |
| خطا پس از اولین بایت جریان | بدنهٔ ناقص با وضعیت ازپیشارسالشدهٔ 200 | Uvicorn |
TestClient(app) | Exception در تست raise میشود | — |
TestClient(app, raise_server_exceptions=False) | پاسخ 500 | — |
اصلاح / روش استفاده: یک Exception handler برای Exception ثبت کنید که با logger.exception و Request id گزارش بنویسد و بدنهٔ عمومی بدهد. str(exc) را هرگز در بدنه نگذارید؛ هر Header لازم را همانجا تنظیم کنید.
حالت اشکالزدایی (Debug mode) مهم
به زبان ساده: FastAPI(debug=True) بدنهٔ 500 را با Traceback کامل جایگزین میکند. روی لپتاپ قابل قبول است؛ در محیط دیگر نشت داده است.
بدفهمی رایج: «Debug فقط پشته را نشان میدهد، نه داده را.» Traceback هم پیام Exception و هم خطوط کد اطراف هر قاب را دارد. در test_debug_true_sends_the_traceback_to_the_client، بدنه شامل Traceback و راز hunter2 داخل پیام بود. بدفهمی دوم: «Exception handler مربوط به Exception در Debug باز اجرا میشود.» Starlette میگوید: "If debug is enabled and an error occurs, then instead of using the installed 500 handler, Starlette will respond with a traceback response."
تعریف: debug به هر دو ServerErrorMiddleware و ExceptionMiddleware داده میشود. ServerErrorMiddleware.debug_response وقتی Accept شامل text/html باشد HTML میسازد و در غیر آن متن ساده؛ در اجرا بدون Accept، پاسخ text/plain بود و با Accept: text/html، پاسخ text/html دارای <title> شد.
FastAPI(debug=True), GET /boom (real)
1 no Accept header -> 500 text/plain "Traceback (most recent call last): ... hunter2"
2 Accept: text/html -> 500 text/html HTML page with frames and source lines
3 installed 500 handler -> not calledسناریوی واقعی: محیط staging تصادفاً با debug=True مستقر شده؛ متغیر محیطی DEBUG با bool(os.getenv("DEBUG")) خوانده شده و حتی برای رشتهٔ "false" مقدار True میدهد؛ همتای Laravel یعنی APP_DEBUG که دربارهاش آمده: "In your production environment, the value of APP_DEBUG should always be false."
| محیط | debug | خطایی که کارخواه میبیند |
|---|---|---|
| محلی | True قابل قبول است | Traceback |
| تست CI | False؛ از raise_server_exceptions=True استفاده کنید | Exception در pytest |
| staging / محیط عملیاتی | همیشه False | Problem عمومی و Request id |
اصلاح / روش استفاده: debug را از تنظیمات نوعدار مثل BaseSettings در Pydantic بخوانید، پیشفرض را False بگذارید و در تست خاموشبودنش در تنظیمات عملیاتی را بررسی کنید؛ APIRouter و ساختار پروژه.
جایگزینی Exception handler مربوط به RequestValidationError مهم
به زبان ساده: وقتی درخواست با امضای تابع سازگار نباشد، FastAPI، RequestValidationError را raise میکند و Exception handler پیشفرض 422 با فهرست detail میدهد. برای تغییر بدنه Exception handler خودتان را ثبت کنید؛ در قطعهکد، Problem با عضو افزودهٔ errors برمیگردد.
بدفهمی رایج: «با این کار Validation پاسخ را هم مدیریت میکنم.» RequestValidationError مربوط به ورودی است؛ خروجی ناسازگار با مدل پاسخ ResponseValidationError میدهد و چون باگ سرور است به گردش 500 میرود. در runs/probe2-output.txt خروجی واقعی Internal Server Error بود و TestClient(app) خطای fastapi.exceptions.ResponseValidationError را raise کرد. بدفهمی دوم: «exc.errors() را بدون تغییر برگردان.» هر خطا input دارد؛ مستندات هشدار میدهند تبدیل Exception به رشته "could be leaking a bit of information about your system". قطعهکد input را حذف میکند؛ درخواست دارای "password":"secret" در پاسخ نه secret داشت نه کلید input.
تعریف: "When a request contains invalid data, FastAPI internally raises a RequestValidationError. And it also includes a default exception handler for it." مقدار exc.errors() فهرستی از dict با type، loc، msg، input و ctx است؛ exc.body بدنهٔ دریافتی است.
POST /orders {"sku":"","qty":99,"password":"secret"} (real)
1 Pydantic: string_too_short at body.sku, less_than_equal at body.qty (extra "password" ignored by the model)
2 raise RequestValidationError(errors)
3 validation_handler -> {"loc", "code", "detail"} per error, no input
4 422 application/problem+json "type": ".../validation", "errors": [...2 entries...]سناریوی واقعی: API با قالب RFC 9457 مشترک میان سرویسها؛ کارخواه موبایل که loc را به فیلد فرم نگاشت میکند؛ ثبت هر شکست Validation که هرگز نباید رمز عبور را در بر داشته باشد.
| موضوع | محل پوشش |
|---|---|
بدنهٔ پیشفرض 422 با type، loc، msg، input و ctx | اعتبارسنجی درخواست |
| بدنهٔ Validation در RFC 9457 با JSON Pointer | اعتبارسنجی درخواست |
ResponseValidationError؛ خروجی خودتان نادرست است | گردش 500 در همین صفحه |
جلوگیری از افشای input | هر دو صفحه |
اصلاح / روش استفاده: یک Exception handler مربوط به Validation در ماژول مشترک problems و مطابق قالب مشترک داشته باشید؛ جزئیات و قالب Pointer در فصل Validation آمده است.
جزئیات مشکل (Problem Details) در RFC 9457 بهعنوان قالب مشترک حیاتی
به زبان ساده: برای همهٔ خطاها یک شکل JSON انتخاب کنید و آن را با application/problem+json بفرستید: type، یک URI برای نام نوع مشکل؛ title؛ status؛ detail برای همین رخداد؛ instance برای محل؛ و عضوهای افزودهٔ خودتان. قطعهکد request_id و زمینهٔ امن مثل sku را اضافه میکند.
بدفهمی رایج: «اطلاعات Debug را در detail میگذاریم.» RFC 9457 میگوید: "The "detail" string, if present, ought to focus on helping the client correct the problem, rather than giving debugging information. Consumers SHOULD NOT parse the "detail" member for information; extensions are more suitable and less error-prone ways to obtain such information." بدفهمی دوم این است که Problem Details جای کد وضعیت را میگیرد. status در بدنه راهنماست؛ Cache، پراکسی و کارخواه بر اساس وضعیت واقعی HTTP عمل میکنند.
تعریف: RFC 9457 در ژوئیهٔ ۲۰۲۳ عضوها و Media type یعنی application/problem+json را تعریف کرد: "This document obsoletes RFC 7807". نبود type به معنای about:blank است. جدول عضوها و قالب 422 در بخش Problem Details فصل Validation است؛ اینجا همان پوشش را برای 404/409/503/500 به کار میبریم.
the snippet's envelope (real bodies)
1 404 {"type":"https://shop.example/problems/order-not-found","title":"Order not found","status":404,
"instance":"/orders/99","request_id":"...","detail":"Order 99 does not exist.","order_id":99}
2 405 {"type":"about:blank","title":"Method Not Allowed","status":405,"instance":"/orders/1",...}
3 500 {"type":"about:blank","title":"Internal Server Error","status":500,...,"detail":"Unexpected error. Quote the request id."}سناریوی واقعی: دروازه (Gateway) همهٔ خطاهای Upstream را یکدست نمایش میدهد؛ کارخواه TypeScript یک نوع خطای مشترک دارد؛ سرویس Go و Python باید خطاهای یکسانی تولید کنند، که هر دو در این دانشنامه آمدهاند.
| عضو | منبع در قطعهکد |
|---|---|
type | TYPE_BASE + slug از DOMAIN_STATUS یا about:blank |
title | جدول نگاشت یا HTTPStatus(code).phrase |
status | وضعیت پاسخ |
detail | exc.detail؛ نوشتهشده برای کارخواه |
instance | request.url.path |
request_id؛ عضو افزوده | ContextVar درخواست |
| زمینه؛ عضو افزوده | exc.context شامل sku، requested، order_id و state |
اصلاح / روش استفاده: همهٔ Exception handlerها یک تابع کمکی problem() را فراخوانی کنند. URIهای type ثابت و مستند باشند. Traceback، SQL و مقدارهای ورودی را در هیچ عضو نگذارید.
نگاشت خطای دامنه (Domain error mapping): OrderNotFound به 404 Not Found و OutOfStock به 409 Conflict حیاتی
به زبان ساده: سرویس با زبان کسبوکار حرف میزند: OrderNotFound، OutOfStock و DuplicateOrder. یک جدول در لایهٔ HTTP تعیین میکند هرکدام چه وضعیت، type و عنوانی داشته باشند. سرویس FastAPI را import نمیکند؛ پس در CLI، پردازشگر (Worker) یا تست بدون HTTP هم قابل استفاده است.
بدفهمی رایج: «تمامشدن موجودی 400 یا 422 است.» درخواست خوشساخت است، ولی وضعیت منبع اجازه نمیدهد. RFC 9110: "The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource." بدفهمی دوم: «خطای پایگاه داده را در Exception handler ترجمه کنیم.» store باید آنها را ترجمه کند، نزدیک به SQL که معنای نقض UNIQUE را میداند: IntegrityError به DuplicateOrder. رسیدن sqlite3.IntegrityError یا IntegrityError خام SQLAlchemy به Exception handler یک 500 است.
تعریف: یک dictionary از کلاس Exception به (status, type slug, title) داریم و با پیمایش MRO آن را میخوانیم. DomainError بدون نگاشت باگ محسوب میشود: 500 و ثبت گزارش. دربارهٔ 404، RFC 9110 میگوید: "the origin server did not find a current representation for the target resource or is not willing to disclose that one exists". SQL تولیدکنندهٔ هر نتیجه چنین است:
-- app/db.py: the schema and the statements whose outcomes become domain errors
CREATE TABLE stock (sku TEXT PRIMARY KEY, available INTEGER NOT NULL CHECK (available >= 0));
CREATE TABLE orders (id INTEGER PRIMARY KEY, sku TEXT NOT NULL REFERENCES stock (sku),
qty INTEGER NOT NULL CHECK (qty > 0),
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'shipped', 'cancelled')),
note TEXT, idempotency_key TEXT UNIQUE);
-- OutOfStock (409): the conditional update touches 0 rows
UPDATE stock SET available = available - :qty WHERE sku = :sku AND available >= :qty;
-- DuplicateOrder (409): UNIQUE (idempotency_key) violation -> IntegrityError, the transaction rolls back
INSERT INTO orders (sku, qty, note, idempotency_key) VALUES (:sku, :qty, :note, :key);
-- OrderNotFound (404): no row
SELECT id, sku, qty, status, note FROM orders WHERE id = :id;
-- OrderNotCancellable (409): 0 rows because status is not 'open'
UPDATE orders SET status = 'cancelled' WHERE id = :id AND status = 'open'; POST /orders twice with Idempotency-Key: k-1 (real)
1 #1 UPDATE stock ... 5 -> 3; INSERT ... key k-1 -> id 2; COMMIT 201 location: /orders/2
2 #2 UPDATE stock ... 3 -> 0; INSERT ... key k-1 -> IntegrityError
3 with-block rolls back both statements; raise DuplicateOrder(...) from exc
4 409 {"type":".../duplicate-order","title":"Duplicate order", ...}
5 #3 qty 3 without a key -> 201 (stock was 3 again: the reservation in #2 was rolled back)سناریوی واقعی: checkout باید «تمام شد» با 409 را از «چنین محصولی نیست» با 404 جدا کند؛ تلاش مجدد بیاثر در تکرار (Idempotent retry) موبایل نباید دوباره وجه بگیرد؛ دکمهٔ لغو سفارش ارسالشده؛ قطعی Dependency که باید با 503 و Retry-After از کارخواه بخواهد دوباره تلاش کند.
| خطای Domain | زمان ایجاد | وضعیت | slug در type | دادهٔ اضافه |
|---|---|---|---|---|
OrderNotFound | SELECT ردیفی نداد | 404 | order-not-found | order_id |
OutOfStock | UPDATE شرطی 0 ردیف را تغییر داد | 409 | out-of-stock | sku، requested |
DuplicateOrder | نقض UNIQUE | 409 | duplicate-order | — |
OrderNotCancellable | وضعیت open نیست | 409 | order-not-cancellable | order_id، state |
PaymentProviderDown | پایان مهلت Upstream | 503 | payment-provider-down | Header با نام Retry-After |
DomainError بدون نگاشت | نگاشت فراموش شده | 500 | unmapped-domain-error | بهعنوان خطا ثبت میشود |
| ORM | «ردیفی نیست» | «قید نقض شد» | نگاشت به |
|---|---|---|---|
sqlite3 در قطعهکد | fetchone() برابر None | sqlite3.IntegrityError | OrderNotFound / DuplicateOrder |
| SQLAlchemy 2 | session.get() مقدار None میدهد؛ نتیجهٔ اجباری NoResultFound را raise میکند: "A database result was required but none was found." | sqlalchemy.exc.IntegrityError: "Wraps a DB-API IntegrityError" | همان |
| SQLModel | session.get(Hero, id) برابر None است؛ آموزش SQLModel سپس HTTPException(404) را raise میکند | IntegrityError در SQLAlchemy | همان؛ در سرویس خطای Domain را به HTTPException ترجیح دهید |
| Alembic | قید UNIQUE مورد اتکای نگاشت را با op.create_unique_constraint اضافه میکند | — | — |
اصلاح / روش استفاده: جدول DOMAIN_STATUS در app/problems.py، یک تست برای هر ردیف، و raise ... from exc هنگام تبدیل تا خطای اصلی در Traceback بماند. الگوهای نشست (Session) و تراکنش (Transaction) در SQLAlchemy 2 و SQLModel آمدهاند.
ثبت خطا با شناسهٔ درخواست (Request id) حیاتی
به زبان ساده: به هر درخواست شناسه بدهید؛ اگر X-Request-ID کارخواه معتبر است همان را بگیرید، وگرنه یکی بسازید. شناسه باید روی هر خط گزارش، در بدنهٔ هر خطا و Header پاسخ باشد. کاربر شناسه را میدهد و شما با یک جستوجو Traceback را پیدا میکنید.
بدفهمی رایج: «در هر Exception handler و هر except گزارش بنویس.» خطای غیرمنتظره را یک بار با Traceback در مرز برنامه، یعنی Exception handler مربوط به 500، ثبت کنید. خطای مورد انتظار Domain سطح INFO دارد، نه ERROR. بدفهمی دوم: «Middleware میتواند شناسه را به 500 اضافه کند.» به پاسخ نمیتواند؛ گردش 500. اما ContextVar تنظیمشده در Middleware در Exception handler قابل خواندن است؛ در اجرا هم رکورد گزارش و هم بدنه req-123 داشتند.
تعریف: دربارهٔ logging.Logger.exception(msg) آمده: "Logs a message with level ERROR on this logger … Exception info is added to the logging message. This method should only be called from an exception handler." یک logging.Filter روی logger با نام shop، مقدار request_id_var.get() را به هر رکورد و %(request_id)s کپی میکند. Middleware یک کلاس خالص ASGI است و از @app.middleware("http") یا BaseHTTPMiddleware استفاده نمیکند؛ بنابراین بدنهٔ جریان را در Task اضافه نمیپیچد.
GET /boom X-Request-ID: req-123 (real, caplog)
1 RequestIdMiddleware: request_id_var.set("req-123")
2 route raises RuntimeError
3 unhandled_handler: log.exception("unhandled RuntimeError on GET /boom") -> record.request_id == "req-123", exc_info set
4 log line: ERROR [req-123] shop: unhandled RuntimeError on GET /boom + traceback
5 response: 500, x-request-id: req-123, body request_id: "req-123"سناریوی واقعی: پشتیبانی مشتری با «شناسهٔ خطا: 4d48dd5a…»؛ مرتبطکردن گزارش FastAPI و سرویس پرداخت با فرستادن X-Request-ID؛ استفاده از شناسهٔ ردگیری (Trace id) در OpenTelemetry بهعنوان Request id.
| سطح | مثال | Traceback دارد؟ |
|---|---|---|
INFO | domain error OutOfStock -> 409 | خیر |
WARNING | تلاش دوبارهٔ Upstream در بار دوم موفق شد | خیر |
ERROR + exc_info | unhandled RuntimeError on GET /boom | بله، یک بار |
ERROR در Uvicorn | Exception in ASGI application بر اثر raise دوباره (Re-raise) | بله |
اصلاح / روش استفاده: observability.py شناسه را در گزارش، Header و بدنه قرار میدهد. شناسهٔ ورودی را محدود و Validation کنید؛ قطعهکد یک تا ۶۴ نویسه را قبول میکند. در فراخوانی خروجی هم شناسه را بفرستید. گزارش ساختیافتهٔ JSON و انتقال گزارش در FastAPI در محیط عملیاتی آمده است.
پارامتر responses و مدل پاسخ خطا (Error response model) مهم
به زبان ساده: Exception handler خروجی کارخواه را تغییر میدهد ولی /docs خبر ندارد. روی هر دکوراتور responses={404: {"model": Problem, ...}} را به OpenAPI معرفی کنید تا کارخواه تولیدشده خطای نوعدار داشته باشد.
بدفهمی رایج: «responses= پاسخ را عوض میکند.» فقط مستند میکند: "for those additional responses you have to make sure you return a Response like JSONResponse directly, with your status code and content"؛ یا خطا raise کنید و ساخت پاسخ را به Exception handler بدهید. نکتهٔ دوم Media type مستندشده است. فقط با model، طرحواره (Schema) زیر application/json میرود. قطعهکد مدخل صریح application/problem+json را هم اضافه میکند؛ تست واقعی test_openapi_documents_error_models. خروجی کامل OpenAPI در بخش responses فصل Validation است.
تعریف: "You can pass to your path operation decorators a parameter responses … Each of those response dicts can have a key model, containing a Pydantic model, just like response_model." کلید model، "is not part of OpenAPI"؛ FastAPI آن را به $ref زیر components.schemas تبدیل میکند.
GET /orders/{order_id} in /openapi.json (real)
1 "200": OrderOut
2 "404": {"description": "Not found", "content": {"application/json": Problem, "application/problem+json": Problem}}
3 "422": FastAPI's HTTPValidationError (added automatically because the route has parameters)سناریوی واقعی: تولیدکنندهٔ SDK که OrderNotFoundError میسازد؛ تست قرارداد (Contract test) که با تغییر شکل خطا شکست میخورد؛ پورتال API که خطاهای هر عملیات را فهرست میکند.
| الگو | کد |
|---|---|
| یک وضعیت | responses={404: PROBLEM_RESPONSES[404]} |
| چند وضعیت | responses={404: ..., 409: ...} |
| در کل router | APIRouter(responses={...}) |
| همراه Header | افزودن "headers": {"Retry-After": {...}} |
| پنهانکردن از مستندات | include_in_schema=False؛ برای /boom و /health در قطعهکد |
اصلاح / روش استفاده: dictionary مشترک PROBLEM_RESPONSES در سطح ماژول تعریف و در هر Route دارای آن وضعیتها استفاده کنید؛ تغییرات /openapi.json را در CI مقایسه کنید.
مقایسهٔ response_model و اعلان نوع بازگشت (Return type annotation) حیاتی
به زبان ساده: FastAPI خروجی شما را با مدل اعتبارسنجی (Validation) و پالایش میکند. مدل را یا در دکوراتور با response_model=OrderOut مینویسید یا در نوع بازگشت تابع با -> OrderOut. هر دو پاسخ را مستند میکنند و فیلدهای خارج از مدل را حذف میکنند.
بدفهمی رایج: «اعلان فقط برای ویرایشگر است.» FastAPI آن را میخواند و مدل پاسخ میداند. بدفهمی دوم: «اگر هر دو باشند اعلان تابع برنده است.» مستندات میگویند: "If you declare both a return type and a response_model, the response_model will take priority and be used by FastAPI." وقتی تابع چیز دیگری مثل dict یا ردیف ORM با ویژگیهای اضافه برمیگرداند، از response_model استفاده کنید؛ وقتی واقعاً مدل برمیگرداند، از اعلان نوع.
تعریف: خروجی با مدل Validation و از طریق همان سریالسازی (Serialisation) میشود؛ فیلد اعلامنشده حذف میشود. در اجرا get_order یک dict با internal_cost_cents برگرداند ولی کارخواه هرگز آن فیلد را نگرفت؛ test_response_model_filters_and_excludes_none. مستندات میگویند: "if you want the maximum performance, use a Response Model and don't declare a response_class in the path operation decorator". علت این است که مدل مستقیم سریالسازی میشود، از 0.130.0 در Rust، و از jsonable_encoder بهاضافهٔ json.dumps نمیگذرد.
GET /orders/1 (real)
1 get_order -> {"id":1,"sku":"BOOK-1","qty":1,"status":"shipped","note":None,"internal_cost_cents":412}
2 response_model=OrderOut: validate, drop internal_cost_cents
3 response_model_exclude_none=True: drop note (None)
4 200 {"id":1,"sku":"BOOK-1","qty":1,"status":"shipped"}سناریوی واقعی: ردیف ORM با هش رمز عبور که نباید افشا شود؛ فیلد هزینهٔ داخلی؛ Endpoint فهرست با خروجی list[OrderOut]؛ Route که گاهی RedirectResponse میدهد. اعلان -> Response یا زیرکلاس Response خودکار مدیریت میشود، اما اجتماع با نوع غیر Pydantic مثل -> Response | dict در مستندات هنگام راهاندازی شکست میخورد؛ راهحل مستندات response_model=None است.
| اعلان | Validation خروجی | پالایش | مستندسازی | بررسی بازگشت در ویرایشگر |
|---|---|---|---|---|
-> OrderOut | بله | بله | بله | بله |
response_model=OrderOut با خروجی dict | بله | بله | بله | خیر |
| هر دو | response_model اولویت دارد | بله | بله | تا حدی |
response_model=None | خیر | خیر | خیر | به انتخاب شما |
بازگرداندن Response | خیر | خیر | فقط با response_class | — |
اصلاح / روش استفاده: اگر مدل برمیگردانید مثل create_order قطعهکد، همان را در نوع بازگشت بنویسید؛ اگر ردیف خام میدهید مثل get_order، از response_model استفاده کنید. مدل ورودی و خروجی جدا باشند. طراحی مدل در Typing و Pydantic v2 باز شده است.
پارامترهای response_model_exclude_unset و response_model_exclude_none مهم
به زبان ساده: این دو پرچم دکوراتور فیلدها را کنار میگذارند. response_model_exclude_unset=True فیلدی را حذف میکند که صریحاً تنظیم نشده؛ مقدار پیشفرض بیرون میماند. response_model_exclude_none=True هر فیلد با مقدار None را حذف میکند.
بدفهمی رایج: «این دو یکی هستند.» در اجرا Preferences(language="fa") با exclude_unset فقط {"language":"fa"} فرستاد و پیشفرضهای newsletter=False و timezone=None حذف شدند. exclude_none در GET /orders/1 فقط note با مقدار null را حذف کرد. بدفهمی دوم: «حذف فیلد بیضرر است.» اگر کارخواه نبود فیلد را متفاوت از false یا null بداند، رفتارش عوض میشود؛ این رفتار را مستند کنید.
تعریف: این پرچمها به Serialisation در Pydantic داده میشوند: "as described in the Pydantic docs for exclude_defaults and exclude_none". پرچم response_model_exclude_defaults هم وجود دارد.
model Preferences(language="en", newsletter=False, timezone=None) (real)
1 stored {"language": "fa"} exclude_unset -> {"language":"fa"}
2 stored {} exclude_unset -> {}
3 Order with note=None exclude_none -> no "note" keyسناریوی واقعی: Endpoint تنظیمات که فقط تغییرهای کاربر را برمیگرداند؛ پاسخ کمفیلد PATCH؛ فهرست بزرگی که nullها حجمش را دو برابر میکنند.
| پرچم | حذف میکند | نگه میدارد |
|---|---|---|
response_model_exclude_unset | فیلد هرگز تنظیمنشده | فیلد تنظیمشده، حتی None |
response_model_exclude_none | فیلد با مقدار None | پیشفرض غیر None |
response_model_exclude_defaults | فیلد برابر پیشفرض | فیلد تغییرکرده |
response_model_include / _exclude | فیلدهای نامبرده | —؛ مدل جدا ترجیح دارد |
اصلاح / روش استفاده: مدل خروجی صریح را ترجیح دهید؛ پرچمها برای سند کمفیلد و تنظیمات مناسباند. JSON دقیق خروجی را تست کنید.
کلاس پاسخ: response_class، JSONResponse، ORJSONResponse، PlainTextResponse، HTMLResponse و RedirectResponse حیاتی
به زبان ساده: کلاس پاسخ Content-Type و تبدیل بدنه به بایت را تعیین میکند. آن را در دکوراتور، مثل response_class=HTMLResponse، بگذارید و محتوا را برگردانید؛ یا Instance را برگردانید.
بدفهمی رایج: «ORJSONResponse انتخاب سریع است.» قبلاً بود. FastAPI 0.131.0 آن را منسوخ کرد و مرجع اکنون میگوید: "FastAPI now serializes data directly to JSON bytes via Pydantic when a return type or response model is set, which is faster and doesn't need a custom response class." در نسخهٔ ثابت 0.128.8 هنوز منسوخ نیست و در اجرا هشداری نداد. README جاری orjson، CPython 3.10+ را میخواهد؛ 3.11.5 آخرین نسخهٔ قابل نصب روی 3.9 است. بدفهمی دوم: «RedirectResponse پاسخ 302 است.» پیشفرض آن 307 است: "Uses a 307 status code by default".
تعریف: "The main Response class, all the other responses inherit from it." Starlette "will automatically include a Content-Length header. It will also include a Content-Type header, based on the media_type and appending a charset for text types." پارامتر response_class نوع رسانه (Media type) را به OpenAPI هم میدهد؛ در اجرا /welcome با text/html مستند شد.
same data, different classes (real)
1 GET /welcome (HTMLResponse) content-type: text/html; charset=utf-8
2 GET /health (PlainTextResponse) "ok"
3 GET /fast/orders/1 (ORJSONResponse) application/json, {"id":1,...,"note":null} (no response_model filtering)
4 GET /legacy/orders/1 (RedirectResponse, 308) location: /orders/1, content-length: 0سناریوی واقعی: بررسی سلامت برای توزیعکنندهٔ بار (Load balancer) با PlainTextResponse؛ callback در OAuth با Redirect، یعنی 303 پس از POST یا 307/308 برای حفظ متد؛ پیشنمایش ایمیل با HTMLResponse؛ URL قدیمی که با 308 زنده نگه داشته میشود.
| کلاس | وضعیت پیشفرض | کد معمول |
|---|---|---|
JSONResponse | 200 | JSONResponse(body, status_code=409, media_type="application/problem+json") |
ORJSONResponse | 200 | از 0.131.0 منسوخ؛ مدل پاسخ را ترجیح دهید |
PlainTextResponse | 200 | response_class=PlainTextResponse + return "ok" |
HTMLResponse | 200 | response_class=HTMLResponse |
RedirectResponse | 307 | RedirectResponse(url, status_code=308) |
| زیرکلاس اختصاصی | — | بازنویسی render()؛ مثال مستندات CustomORJSONResponse با OPT_INDENT_2 |
default_response_class= | — | روی FastAPI() یا APIRouter() برای همهٔ Routeها |
اصلاح / روش استفاده: برای APIهای JSON از مدل پاسخ و بدون response_class استفاده کنید. برای Media type دیگر، response_class= بگذارید تا مستندات درست باشند. برای جابهجایی دائمی Endpoint غیر GET از 308 استفاده کنید.
بازگرداندن مستقیم Response مهم
به زبان ساده: اگر تابع Response یا زیرکلاس آن را برگرداند، FastAPI همان را میفرستد؛ مدل، تبدیل خودکار و Exception handler اجرا نمیشوند.
بدفهمی رایج: «JSONResponse(..., status_code=404) مثل raise است.» در تست واقعی test_returning_a_response_bypasses_handlers، بدنه {"detail":"hand-made"} با application/json بود؛ قالب Problem مشترک نبود، چون Exception handler اجرا نشد. بدفهمی دوم: «مستندات آن را نشان میدهند.» مستندات میگویند: "A Response returned directly by your path operation function won't be documented in OpenAPI."
تعریف: "if you return a Response directly (or any subclass, like JSONResponse), the data won't be automatically converted (even if you declare a response_model)". برای کنترل بایتها و همزمان مستندکردن Media type، هم response_class= را مشخص کنید و هم Instance را برگردانید.
1 return {"id": 1} -> response model -> JSON (documented)
2 return JSONResponse({...}, 404) -> sent as is (handlers skipped, not documented)
3 raise OrderNotFound(...) -> handler -> Problem (documented via responses=)سناریوی واقعی: ساخت دستی 304 یا 204؛ بایت آماده مثل JSON ذخیرهشده در Cache؛ Route که وضعیت خاص هر فراخوانی را خودش تعیین میکند.
| خواسته | انتخاب بهتر |
|---|---|
| وضعیت متفاوت برای خطا | raise؛ ساخت پاسخ با Exception handler |
| وضعیت موفقیت متفاوت در هر فراخوانی | response.status_code = ... روی Response تزریقشده |
| بایت ازپیشساخته | Response(content, media_type=...) |
| Media type در مستندات | response_class= |
اصلاح / روش استفاده: برای موفقیتهایی که مدل JSON نیستند پاسخ را برگردانید؛ برای شکست raise کنید تا قالب مشترک حفظ شود.
Header پاسخ و Set-Cookie روی Response حیاتی
به زبان ساده: پارامتر response: Response را اعلام کنید، response.headers[...] را تنظیم یا response.set_cookie(...) را فراخوانی کنید و همچنان مقدار عادی خودتان را برگردانید. FastAPI سرآیند (Header) و کوکی (Cookie) را روی پاسخ نهایی کپی میکند.
بدفهمی رایج: «تنظیم Header یعنی خودم باید پاسخ بسازم.» شیء تزریقشده دقیقاً برای حذف این نیاز است؛ تعبیر مستندات "temporary response object" است. بدفهمی دوم: «Cookie پیشفرض امن دارد.» پیشفرضهای set_cookie در Starlette، secure=False, httponly=False, samesite="lax" هستند؛ صریح تنظیمشان کنید. خروجی واقعی session=opaque-token; HttpOnly; Max-Age=3600; Path=/; SameSite=lax; Secure بود.
تعریف: امضا Response.set_cookie(key, value, max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax", partitioned=False) است؛ partitioned، "Only available for Python 3.14+" است. delete_cookie آن را منقضی میکند. اگر خودتان Response برمیگردانید، Header را روی همان شیء بگذارید. ویژگیها و امنیت Cookie در اعتبارسنجی درخواست آمدهاند.
POST /session (real)
1 login(response): response.set_cookie("session", "opaque-token", httponly=True, secure=True, samesite="lax", max_age=3600)
2 return {"status": "signed in"}
3 final JSONResponse + set-cookie header merged from the temporal Responseسناریوی واقعی: Location روی 201؛ Set-Cookie پس از ورود؛ Cache-Control روی خواندن قابل Cache؛ ETag؛ Deprecation و Sunset روی Endpoint قدیمی؛ X-Request-ID روی همهٔ پاسخها با Middleware.
| Header | محل تنظیم در FastAPI |
|---|---|
Location | Response تزریقشده در Route ایجاد |
Set-Cookie | response.set_cookie(...) |
Cache-Control، ETag | Route برای هر منبع یا زیرکلاس StaticFiles |
WWW-Authenticate، Retry-After | HTTPException(headers=...) یا Exception handler |
X-Request-ID | Middleware بهاضافهٔ Exception handler مربوط به 500 |
Content-Disposition | FileResponse(filename=...) یا StreamingResponse(headers=...) |
اصلاح / روش استفاده: Header وابسته به درخواست در Route، Header مشترک پاسخها در Middleware، و Header خطا در Exception یا Exception handler قرار میگیرد.
معنای وضعیتها: 201 Created و Location، 204 No Content، 304 Not Modified و مقدمهٔ ETag حیاتی
به زبان ساده: 201 یعنی «ساخته شد و Location میگوید کجاست»؛ 204 یعنی «انجام شد و محتوایی برای ارسال نیست»؛ 304 در پاسخ به درخواست شرطی (Conditional request) دارای If-None-Match میگوید «کپی موجود در Cache هنوز معتبر است».
بدفهمی رایج: «204 یعنی JSON خالی.» یعنی هیچ محتوا. در اجرا FastAPI نه بدنه داد نه Content-Length؛ ولی در 0.128.8 یک Header اضافهٔ content-type: application/json فرستاد، مطابق test_204_has_no_body. dict بازگشتی از Route با وضعیت 204 بیصدا حذف شد؛ runs/probe1-output.txt. بدفهمی دوم: «304 یک Redirect است.» پاسخ به بازاعتبارسنجی (Revalidation) Cache است. RFC 9110 میگوید: "there is no need for the server to transfer a representation of the target resource because the request indicates that the client … already has a valid representation".
تعریف: RFC 9110 دربارهٔ 201 میگوید: "the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location header field is received, by the target URI." دربارهٔ 204: "there is no additional content to send in the response content". سرور سازندهٔ 304، "MUST generate any of the following header fields that would have been sent in a 200 (OK) response"؛ اینها شامل ETag و Cache-Control هستند و باید ارسال شوند. شرح کامل درخواست شرطی، اعتبارسنج ضعیف و قوی (Weak/Strong validator) و If-Match برای قفل خوشبینانه (Optimistic locking) در طراحی REST API و کارهای پسزمینه، Caching و APIهای خارجی است.
receipt route, ETag preview (real)
1 GET /orders/1/receipt 200 etag: "2ef6a3a9edad2da5" cache-control: private, no-cache
2 GET /orders/1/receipt If-None-Match: "2ef6a3a9edad2da5" 304, no body, same etag
3 order changes -> body bytes change -> new etag -> next conditional GET is a 200سناریوی واقعی: POST /orders با 201 و Location: /orders/2؛ DELETE /orders/2 با 204؛ برنامهٔ موبایلی که هر ۳۰ ثانیه وضعیت سفارش را میخواند و اغلب 304 میگیرد؛ PUT با If-Match برای جلوگیری از گمشدن بهروزرسانی.
| وضعیت | بدنه | Headerهای لازم | FastAPI |
|---|---|---|---|
| 200 OK | دارد | — | پیشفرض |
| 201 Created | معمولاً منبع | Location توصیه میشود | status_code=201 + response.headers["Location"] |
| 202 Accepted | منبع وضعیت | Location کار | status_code=202 |
| 204 No Content | ندارد | — | status_code=204 و بازگرداندن None |
| 304 Not Modified | ندارد | ETag/Cache-Control مطابق 200 | Response(status_code=304, headers=...) |
| 409 Conflict | Problem | — | نگاشت خطای Domain |
اصلاح / روش استفاده: کد موفقیت را با status_code= در دکوراتور تعیین کنید، روی هر 201، Location بگذارید و برای 304، Response(status_code=304) با همان Validatorها بدهید. ETag را از هش بایتها یا نسخهٔ ردیف بسازید.
FileResponse: دانلود، درخواست Range و مقدمهٔ بارگذاری مهم
به زبان ساده: FileResponse(path, filename="invoice-1.pdf") فایل دیسک را ناهمگام میفرستد، همراه Content-Length، Last-Modified، ETag و Accept-Ranges: bytes. اگر نام فایل بدهید Content-Disposition: attachment هم میگذارد. درخواست با Range پاسخ 206 میگیرد.
بدفهمی رایج: «فایل را بخوان و بایتها را برگردان.» این کار کل فایل را وارد حافظه میکند و Validator و پشتیبانی Range را از دست میدهد. بدفهمی دوم: «دانلود StreamingResponse لازم دارد.» برای فایل روی دیسک کلاس درست FileResponse است؛ StreamingResponse برای بدنهای است که حین ارسال تولید میشود.
تعریف: Starlette: "Asynchronously streams a file as the response." و "File responses will include appropriate Content-Length, Last-Modified and ETag headers." همچنین: "If the request includes a Range header, and the file exists, the response will be a 206 Partial Content response with the requested range of bytes. If the range is invalid, the response will be a 416 Range Not Satisfiable response." مقدار content_disposition_type پیشفرض "attachment" است و میتواند "inline" باشد.
GET /invoices/1.pdf Range: bytes=0-7 (real, Uvicorn + curl)
1 206 Partial Content content-type: application/pdf accept-ranges: bytes
2 content-disposition: attachment; filename="invoice-1.pdf" content-range: bytes 0-7/193 content-length: 8
3 body: %PDF-1.4سناریوی واقعی: دانلود فاکتور و گزارش پس از احراز هویت؛ ادامهٔ دانلود خروجی بزرگ؛ رفتن به بخش دیگری از ویدئو با Range؛ بارگذاری با UploadFile که Starlette موقتاً روی دیسک میریزد و پس از Validation به ذخیرهسازی شیء (Object storage) میدهید. تجزیهٔ بارگذاری در اعتبارسنجی درخواست، و URL ازپیشامضاشده و تحویل CDN در بارگذاری فایل، S3 و CDN است.
| نیاز | ابزار |
|---|---|
| فایل دیسک محلی | FileResponse(path, filename=...) |
| نمایش در مرورگر | content_disposition_type="inline" |
| فایل تولیدی؛ CSV یا ZIP در لحظه | StreamingResponse + Content-Disposition |
| فایل S3 | Redirect با 307 به URL ازپیشامضاشده؛ بایتها را پراکسی نکنید |
| بارگذاری | UploadFile ← بررسی اندازه و نوع ← Object storage |
اصلاح / روش استفاده: ابتدا مجوز (Authorization) را بررسی کنید؛ قطعهکد پیش از ساخت پاسخ OrderNotFound را raise میکند. بعد FileResponse بسازید. Path را بدون نرمالسازی از ورودی کاربر نسازید.
StreamingResponse: مولد (Generator)، Async generator و Chunked transfer encoding حیاتی
به زبان ساده: StreamingResponse(gen(), media_type="text/csv") وضعیت و Header را فوراً میفرستد، سپس بهازای هر yield یک قطعه. طول کل معلوم نیست؛ بنابراین HTTP/1.1 بدنه را با کدگذاری انتقال قطعهای (Chunked transfer encoding) قاببندی میکند. کارخواه پیش از پایان نوشتن شما شروع به خواندن میکند.
بدفهمی رایج: «پیچیدن list در iter() آن را جریانی میکند.» برنامهٔ پیش از اصلاح اول همهٔ ۱۰٬۰۰۰ ردیف را میساخت و بعد «جریان» میفرستاد؛ حافظه و انتظار همان بود. تولید باید تنبل (Lazy) باشد. بدفهمی دوم: «Async generator همیشه بهتر است.» Generator همگام با iterate_in_threadpool در Thread pool پیمایش میشود و جای درست خواندن Blocking از فایل یا cursor همگام DB است. Async generator روی Event loop اجرا میشود و باید فقط فراخوانی غیر Blocking را await کند.
تعریف: Starlette: "Takes an async generator or a normal generator/iterator and streams the response body." و "Have in mind that file-like objects (like those created by open()) are normal iterators." بخش ۷٫۱ در RFC 9112 میگوید: "Chunked enables content streams of unknown size to be transferred as a sequence of length-delimited buffers". در HTTP/2 و HTTP/3 همین جریان در قابهای DATA میرود و Transfer-Encoding استفاده نمیشود؛ تکامل HTTP. در FastAPI 0.134.0+ میتوانید response_class=StreamingResponse بگذارید و مستقیماً در Path operation، yield کنید. مستندات این شیوه را توصیه میکنند چون "it's much more convenient and handles cancellation behind the scenes for you".
GET /stream/ticks?n=3 (real, Uvicorn 0.39.0 + curl -si)
1 StreamingResponse.__call__: task group { stream_response(send), listen_for_disconnect(receive) }
2 send http.response.start 200 content-type: text/plain; charset=utf-8 (no content-length)
3 Uvicorn adds: transfer-encoding: chunked
4 yield b"tick 0\n" -> send body chunk (more_body=True) -> "7\r\ntick 0\n\r\n" on the wire
5 ... tick 1, tick 2
6 send body b"" (more_body=False) -> "0\r\n\r\n"; task group cancels the disconnect listenerسناریوی واقعی: CSV یک میلیون سفارش؛ پراکسی پاسخ بزرگ Upstream بدون بافرکردن کامل؛ JSON Lines با application/jsonl برای دنبالکردن گزارش؛ ZIP تولیدی؛ بدنهٔ همهٔ Endpointهای SSE.
| تولیدکننده | محل اجرا | کاربرد | فراخوانی Blocking داخل آن؟ |
|---|---|---|---|
Generator همگام؛ def gen(): yield | Thread pool، هر بار یک عضو | خواندن فایل، cursor همگام DB، نویسندهٔ CSV | مجاز |
Async generator؛ async def gen(): yield | Event loop | httpx.AsyncClient.stream، driver ناهمگام DB، جریان SDK مدل | هرگز |
شیء فایل؛ open(...) | Thread pool | FileResponse را ترجیح دهید | مجاز |
yield در Path operation از 0.134.0+ | مانند بالا | همان کاربرد با لغو مدیریتشدهٔ FastAPI | مانند بالا |
زیرکلاس StreamingResponse با media_type | — | Content-Type ثابت؛ PNGStreamingResponse مستندات | — |
اصلاح / روش استفاده: Generator باید قطعهٔ معقول تولید کند؛ خروجی CSV قطعهکد تقریباً هر ۸ KiB تخلیه میشود، نه با یک نوشتن برای هر ردیف. همیشه media_type و برای دانلود Content-Disposition را تنظیم کنید.
فشار برگشتی (Back-pressure) حیاتی
به زبان ساده: اگر کارخواه کندتر از تولید شما بخواند، Generator صبر میکند. پس از هر yield، یک await send(...) هست که تا پر بودن بافرهای سوکت برنمیگردد. مصرف حافظه به اندازهٔ بافرها محدود میماند، نه اندازهٔ کل خروجی.
بدفهمی رایج: «کارخواه کند سرور را وادار میکند کل پاسخ را بافر کند.» با Generator چنین نیست. در آزمایش واقعی test_back_pressure_pauses_the_producer روی loopback در macOS و بافر دریافت ۱۶ KiB، کارخواه نیمثانیه هیچچیز نخواند؛ تولیدکننده فقط ۱۸ قطعه از ۵۱۲ قطعهٔ ۶۴ KiB جلو رفت، یعنی ۱۱۵۲ KiB، سپس با خواندن کارخواه ادامه داد. سه اجرا همان ۱۸ را نشان دادند. بدفهمی دوم: «پس Back-pressure همهجا خودکار است.» وقتی تولیدکننده و فرستنده را جدا کنید این خاصیت از بین میرود؛ مثلاً Task پسزمینهای که asyncio.Queue نامحدود را پر میکند یا list که پیش از اولین yield ساخته شده است.
تعریف: پروتکل HTTP در Uvicorn از callbackهای کنترل جریان (Flow control) در asyncio استفاده میکند. با عبور بافر نوشتن از حد بالایی (High-water mark)، asyncio، pause_writing() را صدا میزند؛ Uvicorn، write_paused را تنظیم میکند و send تا resume_writing() در await self.flow.drain() میماند. کدهای flow_control.py و httptools_impl.py نسخهٔ 0.39.0 ذخیره شدهاند. کانال محدود میان Taskها، مثل anyio.create_memory_object_stream(10) در README بستهٔ sse-starlette، با پرشدن بافر تولیدکننده را نگه میدارد و این ویژگی را حفظ میکند.
slow reader, /stream/big?chunks=512&size=65536 (real)
1 gen yields chunk 1..n; each send() writes into the transport buffer
2 kernel send/receive buffers fill (client reads nothing)
3 asyncio -> pause_writing(); next send(): await flow.drain() <- generator suspended at its yield (chunk 18)
4 0.5 s later the client starts reading; buffers empty; resume_writing() -> drain() returns
5 generator continues; all 32 MiB delivered; peak memory ~ buffers, not 32 MiBسناریوی واقعی: موبایل با شبکهٔ کند خروجی بزرگ میگیرد؛ مصرفکنندهٔ SSE متوقف شده؛ پراکسی آهسته میخواند؛ چندین مصرفکنندهٔ کند همزمان. هرکدام اتصال (Connection) و Generator معلق نگه میدارند؛ حافظهٔ کمی میخواهند ولی در --limit-concurrency در Uvicorn حساب میشوند.
| طراحی | حافظه محدود میماند؟ | دلیل |
|---|---|---|
| Generator همزمان با خواندن yield میکند | بله | await send تولیدکننده را نگه میدارد |
| کانال حافظه با ظرفیت 10 | بله | تولیدکننده پشت کانال پر میایستد |
asyncio.Queue نامحدود که Task پر میکند | خیر | تولیدکننده هرگز منتظر نمیماند |
| اول list، بعد جریان | خیر | پیش از اولین بایت همهچیز در حافظه است |
| خواندن کامل Upstream، سپس return | خیر | همان دلیل |
اصلاح / روش استفاده: تولید را داخل Generator نگه دارید یا کانال محدود بگذارید. مانند آزمایشگاه با کارخواه کند اندازه بگیرید. مهلت هر Connection و حد همزمانی تنظیم سرور است؛ FastAPI در محیط عملیاتی.
قطع اتصال کارخواه (Client disconnect) و request.is_disconnected حیاتی
به زبان ساده: با رفتن کارخواه، Starlette جریان را لغو میکند؛ Generator در await بعدی CancelledError میگیرد، finally: اجرا میشود و دیگر چیزی ارسال نمیشود. بین قطعهها میتوانید با await request.is_disconnected() هم وضعیت را بپرسید و خودتان تمام کنید.
بدفهمی رایج: «سرور فوراً Disconnect را میفهمد و کار را متوقف میکند.» توقف فقط در await ممکن است. مستندات: "An async task can only be cancelled when it reaches an await. If there is no await, the generator (function with yield) can not be cancelled properly and may keep running even after cancellation is requested." حلقهٔ CPU یا فراخوانی Blocking ادامه مییابد. بدفهمی دوم: «فقط is_disconnected() کافی است.» این بررسی را باید خودتان صدا بزنید؛ چیزی که Generator منتظر I/O بالادست را متوقف میکند لغو است.
تعریف: وقتی spec_version در ASGI سرور پایینتر از 2.4 باشد، StreamingResponse.__call__ در Starlette، stream_response و listen_for_disconnect را در یک گروه وظیفه (Task group) اجرا میکند. Uvicorn 0.39.0 مقدار "spec_version": "2.3" میفرستد. شنونده منتظر http.disconnect میماند و گروه را لغو میکند. مستندات Requests در Starlette: "In some cases such as long-polling, or streaming responses you might need to determine if the client has dropped the connection. You can determine this state with disconnected = await request.is_disconnected()."
curl -sN --max-time 0.2 "/stream/ticks?n=10000&delay=0.01" (real)
1 curl prints tick 0 .. tick 17, then closes the socket at 0.2 s
2 Uvicorn: connection_lost -> receive() returns {"type": "http.disconnect"}
3 listen_for_disconnect returns -> task group cancelled
4 generator: CancelledError at `await asyncio.sleep(delay)` -> except: log; finally: cleanup
5 log: INFO [7e8503…] shop: ticks cancelled after 18 chunks (client disconnected)
test_live.py: STREAM_EVENTS == ["ticks: cancelled after 3", "ticks: cleanup"]سناریوی واقعی: کاربر وسط گزارش دو دقیقهای زبانه را میبندد؛ جریان LLM پس از رفتن خواننده همچنان هزینهٔ توکن میسازد؛ Endpoint با long-poll؛ فید SSE که مصرفکنندهاش به صفحهٔ دیگری رفته است.
| وضعیت | چه چیزی کار را متوقف میکند؟ |
|---|---|
Generator منتظر I/O؛ await upstream یا await sleep | لغو با CancelledError؛ اجرای finally: |
| Generator بین قطعهها | بررسی await request.is_disconnected() |
حلقهٔ CPU بدون await | هیچچیز؛ await anyio.sleep(0) اضافه کنید یا کار را به Worker بدهید |
| Generator همگام در Thread pool | پیمایش متوقف میشود؛ نخ عضو فعلی را تمام میکند |
کار آغازشده با BackgroundTasks | ادامه پیدا میکند؛ پس از پاسخ اجرا میشود، پایینتر ببینید |
اصلاح / روش استفاده: هر تکرار یک await داشته باشد؛ منابع Upstream را در try/finally ببندید، مثل جریان HTTP و cursor DB. با except CancelledError: ...; raise خطای لغو را دوباره بالا بفرستید و هرگز نبلعید. لغو را با سطح INFO ثبت کنید.
خطا در میانهٔ جریان (Errors in the middle of a stream) مهم
به زبان ساده: پس از اولین بایت، وضعیت 200 و Headerها فرستاده شدهاند. Exception بعدی دیگر نمیتواند 404 یا 500 بسازد؛ اتصال قطع میشود و کارخواه بدنهٔ ناقص میبیند.
بدفهمی رایج: «Exception handler مربوط به Exception یک Problem میفرستد.» نمیتواند؛ ServerErrorMiddleware فقط با شرط if not response_started پاسخ خود را ارسال میکند. در runs/midstream-error-live.txt، curl عبارت part 1 را چاپ کرد و با کد خروج ۱۸، یعنی فایل ناقص، تمام شد. httpx خطای RemoteProtocolError: peer closed connection without sending complete message body (incomplete chunked read) داد و Uvicorn، Exception in ASGI application را با ExceptionGroup حاصل از Task group پاسخ ثبت کرد.
تعریف: وضعیت و Header در http.response.start قرار دارند و پس از آن فقط http.response.body است. بدنهٔ Chunked بدون پایاندهندهٔ 0\r\n\r\n در HTTP/1.1 ناقص است. حتی Exception مدیریتشده پس از شروع هم کمکی نمیکند؛ wrap_app_handling_exceptions در Starlette 0.49.3 خطای RuntimeError("Caught handled exception, but response already started.") را raise میکند؛ کد ذخیره شده است.
generator: yield b"part 1\n"; raise RuntimeError("upstream died") (real)
1 200 + headers sent, chunk "part 1" sent
2 exception -> task group -> ServerErrorMiddleware: response_started is True -> no 500, re-raise
3 Uvicorn closes the connection without the final chunk
4 client: incomplete chunked readسناریوی واقعی: Connection پایگاه داده در ردیف ۶۰۰٬۰۰۰ خروجی قطع میشود؛ ارائهدهندهٔ LLM بعد از ۲۰۰ توکن خطا میدهد؛ واسطهٔ پیام (Message broker) بالادست فید SSE دوباره اجرا میشود.
| پروتکل | اعلام خطای دیرهنگام |
|---|---|
| جریان ساده / CSV | قطع ناقص؛ کارخواه باید کاملبودن را با تعداد ردیف یا خط پایانی بررسی کند |
| JSON Lines | خط نهایی {"error": ...} با قرارداد شناختهشدهٔ کارخواه |
| SSE | event: error با data: شبیه Problem؛ مانند جریان chat قطعهکد |
| همه | بررسی هر چیز ممکن پیش از اولین yield؛ احراز هویت، وجود منبع، سهمیه |
اصلاح / روش استفاده: بررسیهایی که میتوانند وضعیت شکست داشته باشند پیش از بازگرداندن StreamingResponse انجام شوند. داخل Generator خطاهای قابل توصیف را بگیرید و رویداد خطای درونجریان (In-band) بسازید؛ بقیه جریان را ناقص میکنند و ثبت میشوند.
رویدادهای ارسالی سرور (Server-Sent Events): text/event-stream، شناسه، retry و Last-Event-ID حیاتی
به زبان ساده: SSE جریان یکطرفهٔ رویداد متنی روی پاسخ معمولی HTTP با Content-Type: text/event-stream است. هر رویداد چند خط field: value و سپس یک خط خالی دارد. مرورگر با EventSource آن را میخواند، خودکار دوباره وصل میشود و آخرین id دیدهشده را در Last-Event-ID میفرستد.
بدفهمی رایج: «SSE سرور ویژه میخواهد.» همان HTTP قطعهای است؛ هر StreamingResponse با قاببندی (Framing) و Header درست، SSE است. بدفهمی دوم: «هر yield یک رویداد است.» فقط خط خالی رویداد را تحویل میدهد. برنامهٔ پیش از اصلاح با yield json.dumps(...) خروجی {"n": 0}{"n": 1}{"n": 2} میداد که EventSource هرگز آن را رویداد نمیداند.
تعریف: بخش ۹٫۲ در WHATWG HTML: "This event stream format's MIME type is text/event-stream." دربارهٔ خطها: "If the line is empty (a blank line) Dispatch the event"؛ و "If the line starts with a U+003A COLON character (😃 Ignore the line" که همان توضیح است. فیلد event نوع رویداد را مشخص میکند. data با نویسهٔ خط جدید به داده اضافه میشود؛ پس دادهٔ چندخطی چند خط data: میخواهد. id آخرین شناسه را تنظیم میکند. دربارهٔ retry آمده: "If the field value consists of only ASCII digits, then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer". مرورگر در اتصال مجدد Header با نام Last-Event-ID را تنظیم میکند.
EventSource("/sse/orders") (real framing, snippet)
1 : stream opened comment, ignored
2 retry: 5000 reconnect after 5 s
3 event: order / id: 0 / data: {"id": 1, "status": "paid"} -> "order" event, lastEventId "0"
4 event: order / id: 1 / data: {... "packed"} -> lastEventId "1"
5 -- connection drops --
6 browser waits 5000 ms, GET /sse/orders Last-Event-ID: 1
7 server resumes at seq 2: event: order / id: 2 / data: {... "shipped"} (real: test_last_event_id_resumes)سناریوی واقعی: تغییر وضعیت سفارش در صفحهٔ پیگیری؛ اعلان؛ پیشرفت کار طولانی؛ گزارش زنده؛ جریان توکن گفتوگوی AI. مستندات میگویند: "SSE is commonly used for AI chat streaming, live notifications, logs and observability". پروتکلهایی مثل MCP هم به تعبیر مستندات FastAPI، "stream SSE over POST".
| فیلد | معنا | قطعهکد |
|---|---|---|
data: | خط یا خطهای محتوا؛ معمولاً JSON | data: {"id": 1, "status": "paid"} |
event: | نوع رویداد؛ addEventListener("order", ...)؛ پیشفرض message | event: order |
id: | آخرین شناسه؛ بازگشت در Last-Event-ID | id: 0 |
retry: | زمان اتصال مجدد بر حسب ms | retry: 5000 |
توضیح : | نادیده گرفته میشود؛ برای Keep-alive | : keep-alive |
| خط خالی | تحویل رویداد | \n\n |
| Content type | text/event-stream | media_type="text/event-stream" |
اصلاح / روش استفاده: sse_frame() قطعهکد یک تابع تستشده است. برای هر رویداد قابل ادامه id بدهید، Last-Event-ID را با Header() بخوانید، یک بار در شروع retry: بفرستید و Headerهای بخش پراکسیها را اضافه کنید.
پیادهسازی SSE: دستی، EventSourceResponse در sse-starlette و fastapi.sse مهم
به زبان ساده: سه راه برای SSE در FastAPI هست: قاببندی دستی روی StreamingResponse مثل /sse/orders؛ کلاس EventSourceResponse بستهٔ ثالث sse-starlette مثل /sse/lib؛ یا در FastAPI 0.135.0+، کلاس fastapi.sse.EventSourceResponse با yield در Path operation.
بدفهمی رایج: «EventSourceResponse یک کلاس است.» دو کلاس همنام داریم: sse_starlette.EventSourceResponse که دور Generator ساخته میشود، و fastapi.sse.EventSourceResponse که response_class عملیات دارای yield است. بدفهمی دوم: «بایتهای کتابخانه با خروجی من یکساناند.» در اجرای واقعی sse-starlette 3.3.0 جداکنندهٔ پیشفرض \r\n از پارامتر sep بود؛ Headerهای Cache-Control: no-store، Connection: keep-alive و X-Accel-Buffering: no را گذاشت و هر ۱۵ ثانیه ping میفرستد.
تعریف: sse-starlette خود را چنین معرفی میکند: "Production ready Server-Sent Events implementation for Starlette and FastAPI following the W3C SSE specification". پارامترها شامل ping با پیشفرض ۱۵ و توضیح "0 disables keep-alive pings"، همچنین sep، send_timeout، shutdown_event و shutdown_grace_period هستند. مستندات FastAPI 0.135.0 میگویند: "To stream SSE with FastAPI, use yield in your path operation function and set response_class=EventSourceResponse" و "Each yielded item is encoded as JSON and sent in the data: field". کلاس ServerSentEvent فیلدهای event، id، retry و comment را میگیرد؛ raw_data متن ازپیشقالببندیشده مثل [DONE] را میفرستد. همچنین "FastAPI implements some SSE best practices out of the box": توضیح ping زندهنگهدارنده "every 15 seconds"، Cache-Control: no-cache و X-Accel-Buffering: no.
# FastAPI 0.135.0+ only (described from the docs; not run on the 0.128.8 pin)
from collections.abc import AsyncIterable
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent
app = FastAPI()
@app.get("/orders/events", response_class=EventSourceResponse)
async def order_events() -> AsyncIterable[ServerSentEvent]:
for seq, status in enumerate(["paid", "packed", "shipped"]):
yield ServerSentEvent(data={"id": 1, "status": status}, event="order", id=str(seq))دستی با StreamingResponse | sse-starlette 3.3.0 | fastapi.sse از 0.135.0+ | |
|---|---|---|---|
| نصب | هیچ بستهٔ اضافه | sse-starlette؛ نسخهٔ 3.7.1 به Python 3.11+ نیاز دارد | FastAPI ≥ 0.135.0 |
| Framing | sse_frame() خودتان | ServerSentEvent یا dict | ServerSentEvent، data کدگذاریشدهٔ JSON |
| جداکنندهٔ خط | \n در قطعهکد | پیشفرض \r\n | طبق مستندات |
| ping زندهنگهدارنده | حلقهٔ خودتان | ping=15 | هر 15 ثانیه |
Cache-Control | no-store را خودتان میگذارید | no-store | no-cache؛ ذخیره با بازاعتبارسنجی؛ اگر هیچ Cache نباید نگه دارد no-store اضافه کنید |
X-Accel-Buffering: no | خودتان تنظیم میکنید | بله | بله |
| مدیریت Disconnect | لغو و بررسی خودتان | داخلی | داخلی |
| خاموشی | سرور لغو میکند | shutdown_event و مهلت پایان | سرور لغو میکند |
| دادهٔ نوعدار در OpenAPI | خیر | خیر | AsyncIterable[Item] مستند و Validation میشود |
اصلاح / روش استفاده: روی FastAPI جاری از fastapi.sse استفاده کنید. روی نسخههای قدیمی ثابت، مثل قطعهکد، sse-starlette یا sse_frame() تستشده مناسب است. دو قاببندی را در یک جریان مخلوط نکنید.
پراکسی، بافرکردن (Proxy buffering)، X-Accel-Buffering و کامنتهای Keep-alive (Keep-alive comments) حیاتی
به زبان ساده: جریان مستقیم از Uvicorn ممکن است پشت Nginx، Load balancer یا CDN یکجا برسد یا مهلتش تمام شود؛ آنها پاسخ را بافر و اتصال (Connection) بیکار را میبندند. با X-Accel-Buffering: no به Nginx بگویید بافر نکند؛ با Cache-Control: no-store جلوی ذخیره را بگیرید، چون no-cache هنوز ذخیره را مجاز میداند. تقریباً هر ۱۵ ثانیه یک خط توضیح بفرستید تا Connection بیکار به نظر نرسد.
بدفهمی رایج: «کد من هر قطعه را flush میکند، پس کارخواه همان لحظه میگیرد.» Nginx با proxy_buffering on که پیشفرض است، "receives a response from the proxied server as soon as possible, saving it into the buffers". کارخواه تا پرشدن بافر یا پایان پاسخ چیزی نمیبیند. بدفهمی دوم: «Keep-alive comment برای مرورگر است.» برای تجهیزات بین راه است. WHATWG میگوید: "Legacy proxy servers are known to, in certain cases, drop HTTP connections after a short timeout. To protect against such proxy servers, authors can include a comment line (one starting with a ':' character) every 15 seconds or so."
تعریف: پیشفرض proxy_buffering در Nginx برابر on است: "When buffering is disabled, the response is passed to a client synchronously, immediately as it is received." همچنین "Buffering can also be enabled or disabled by passing "yes" or "no" in the "X-Accel-Buffering" response header field." پیشفرض proxy_read_timeout برابر ۶۰ ثانیه است و "is set only between two successive read operations"؛ به همین دلیل ping پانزدهثانیهای جریان را زنده نگه میدارد. WHATWG هشدار دیگری هم دارد: "HTTP chunking can have unexpected negative effects on the reliability of this protocol, in particular if the chunking is done by a different layer unaware of the timing requirements".
behind Nginx, defaults, no X-Accel-Buffering (expected, not run)
1 app sends event 1 at t=0 s, event 2 at t=5 s
2 Nginx buffers both (proxy_buffering on); client sees nothing
3 t=60 s no new bytes -> proxy_read_timeout -> Nginx closes the upstream connection
with X-Accel-Buffering: no + ": keep-alive" every 15 s:
4 each event reaches the client immediately; the ping resets the 60 s read timerسناریوی واقعی: صفحهٔ SSE محلی درست است ولی در محیط عملیاتی «فقط با تمامشدن درخواست تازه میشود»؛ مهلت بیکاری Load balancer جریان ساکت را میبندد؛ CDN اولین پاسخ جریان رویداد را برای همهٔ کاربران Cache میکند؛ مستندات Laravel هم همان Header را میگذارند: response()->stream(..., 200, ['X-Accel-Buffering' => 'no']).
| لایه | مشکل | اصلاح |
|---|---|---|
| Nginx | proxy_buffering on | X-Accel-Buffering: no در هر پاسخ یا proxy_buffering off; در location |
| Nginx | proxy_read_timeout 60s | توضیح Keep-alive تقریباً هر 15 ثانیه یا افزایش مهلت آن location |
| هر Cache / CDN | ذخیرهٔ جریان | Cache-Control: no-store؛ MDN دربارهٔ no-cache: "allows caches to store a response but requires them to revalidate it before reuse"؛ قاعدهٔ عبور بدون Cache برای text/event-stream |
| Load balancer | مهلت بیکاری | فاصلهٔ ping کمتر از مهلت |
| فشردهسازی؛ GZip middleware یا gzip پراکسی | نگهداشتن بایت تا پرشدن بلوک | مستثناکردن text/event-stream |
| مرورگر HTTP/1.1 | حد MDN، "is per browser + domain" و "set to a very low number (6)" | اشتراک یک EventSource با shared worker یا HTTP/2 |
اصلاح / روش استفاده: از SSE_HEADERS قطعهکد و کامنتهای Keep-alive (Keep-alive comments) استفاده کنید. تنظیم Nginx در FastAPI در محیط عملیاتی و توزیع رویداد میان چند سرور (Fan-out) در ارتباط بلادرنگ آمده است.
جریان توکن LLM (LLM token streaming) مهم
به زبان ساده: Endpoint گفتوگو ارائهدهندهٔ مدل را با Streaming فعال فراخوانی میکند. هر توکن یا تغییر جزئی (Delta) بلافاصله بهشکل رویداد SSE به مرورگر میرود و در پایان نشانگر (Sentinel) مثل data: [DONE] میآید. کاربر بهجای انتظار برای پاسخ کامل، حدود یک ثانیه بعد ظاهرشدن متن را میبیند.
بدفهمی رایج: «با بستن زبانه تولید مدل متوقف میشود.» فقط اگر جریان Upstream را ببندید. chat_stream در قطعهکد، is_disconnected() را بررسی میکند و همیشه در finally: روی iterator توکن aclose() میزند؛ در اجرا llm: upstream closed ثبت شد. بدفهمی دوم: «خطا پاسخ 5xx میدهد.» پس از اولین توکن دیگر نمیشود؛ event: error بفرستید؛ خطای میانهٔ جریان.
تعریف: الگو یک Async generator است که جریان ناهمگام SDK ارائهدهنده را میخواند و قاب SSE میدهد؛ هم SDK سازگار با OpenAI و هم SDK بومی چنین جریانی دارند. مستندات SSE در FastAPI، raw_data را برای "special "sentinel" values like [DONE]" نشان میدهند. قالب سمت ارائهدهنده، شمارش توکن و Retry در APIهای LLM در عمل و Endpoint کامل RAG در پروژهٔ FastAPI AI/RAG است.
POST /chat/stream {"prompt":"hi"} (real, fake provider)
1 validate body, auth, quota (before the first byte: errors are still real statuses)
2 tokens = fake_llm_tokens(prompt) # stand-in for an SDK stream
3 async for token in tokens: yield "event: token\ndata: {\"delta\": \"You \"}\n\n" ...
4 yield "data: [DONE]\n\n"
5 finally: await tokens.aclose() -> "llm: upstream closed"سناریوی واقعی: ربات پشتیبانی؛ تکمیل کد؛ خلاصهسازی سند هنگام مشاهدهٔ کاربر؛ عامل که پیشرفت ابزار را با رویداد نامدار مثل event: tool و event: token میفرستد.
| مرحله | قاعده |
|---|---|
| پیش از Streaming | احراز هویت، Validation، سهمیه و محدودیت نرخ |
| هنگام Streaming | await برای هر توکن، بررسی is_disconnected() و قاب کوچک |
| هنگام Disconnect | بستن جریان ارائهدهنده برای توقف هزینه |
| خطای ارائهدهنده | event: error با محتوای شبیه Problem، سپس پایان |
| پایان | Sentinel مثل [DONE] یا event: end؛ در صورت نیاز مصرف در رویداد نهایی |
| پشت پراکسی | همان Headerها و pingهای SSE |
اصلاح / روش استفاده: شکل /chat/stream قطعهکد را بگیرید و fake_llm_tokens را با جریان SDK عوض کنید. فراخوانی ارائهدهنده داخل BackgroundTasks نباشد؛ باید به Connection کارخواه وابسته بماند.
StaticFiles: نصب، html=True، Cache-Control فایل ایستا و CDN مهم
به زبان ساده: app.mount("/app", StaticFiles(directory="static", html=True)) فایلهای یک پوشه را زیر /app سرو میکند. با html=True، نشانی /app/ فایل index.html را میدهد و نبود فایل، اگر 404.html موجود باشد، همان را میدهد.
بدفهمی رایج: «StaticFiles Headerهای Cache را تنظیم میکند.» Validatorهای ETag و Last-Modified و پاسخ شرطی 304 را دارد، که در اجرا دیده شد؛ ولی Cache-Control ندارد. زیرکلاس CachedStaticFiles قطعهکد برای فایل دارای اثرانگشت محتوا (Fingerprinted asset)، public, max-age=31536000, immutable و برای HTML، no-cache میگذارد. بدفهمی دوم: «نصب برنامه (Mount) مثل router است.» مستندات: "a mounted application is completely independent. The OpenAPI and docs from your main application won't include anything from the mounted application". Mount روی / همهٔ Pathهای تطبیقنیافته را میگیرد.
تعریف: امضا StaticFiles(directory=None, packages=None, html=False, check_dir=True, follow_symlink=False) است. html یعنی "Run in HTML mode. Automatically loads index.html for directories if such file exist." همچنین "Static files will respond with "404 Not found" or "405 Method not allowed" responses for requests which do not match. In HTML mode if 404.html file exists it will be shown as 404 response." مستندات جاری FastAPI برای Frontend به app.frontend() اشاره میکنند؛ از 0.138.0 در ۲۰ ژوئن ۲۰۲۶، که "uses StaticFiles underneath, with several additional advantages for frontends, like handling client-side routing".
/app mount, html=True (real)
1 GET /app/ 200 index.html cache-control: no-cache etag: "135ff0…"
2 GET /app/ If-None-Match: "135ff0…" 304, no body
3 GET /app/assets/app.3f9a1c.css 200 cache-control: public, max-age=31536000, immutable
4 GET /app/nope.html 404 with 404.html POST /app/ 405
5 GET /app/../main.py 404 (path traversal refused)سناریوی واقعی: برنامهٔ تکصفحهای (SPA) مدیریت همراه API؛ سایت مستندات؛ آواتار بارگذاریشده فقط در توسعه. در محیط عملیاتی و مقیاس بالا، Nginx یا CDN باید فایلها را سرو کنند: Range، فشردهسازی، sendfile و Cache لبه را بدون اشغال Workerهای Python انجام میدهند.
سروکنندهٔ /assets/* | مناسب برای | Cache-Control |
|---|---|---|
StaticFiles در برنامه | توسعه و ابزار داخلی کوچک | خودتان با زیرکلاس اضافه کنید |
Nginx جلوی برنامه؛ location /assets/ | یک منطقه با درخواست زیاد | expires max; / immutable |
| CDN؛ CloudFront، Cloudflare، Fastly | کاربران جهانی و فایل بزرگ | max-age طولانی و نام دارای اثرانگشت |
| Object storage + CDN | بارگذاری کاربران | برای هر شیء |
اصلاح / روش استفاده: نام فایل دارای اثرانگشت مثل app.3f9a1c.css را با immutable، فایل index.html را با no-cache و Mount را زیر پیشوند غیرریشه بگذارید. با رشد ترافیک یا اندازهٔ فایل CDN بیاورید؛ بارگذاری فایل، S3 و CDN.
مقدمهٔ BackgroundTasks تکمیلی
به زبان ساده: tasks.add_task(fn, *args) تابع fn را پس از ارسال پاسخ در همان پردازه (Process) اجرا میکند؛ برای ایمیل تأیید، گزارش حسابرسی و گرمکردن Cache.
بدفهمی رایج: «خطای Task پسزمینه به کارخواه 500 میدهد.» پاسخ قبلاً رفته است. Starlette میگوید: "in case a BackgroundTask raises an exception, it will be handled by the handle_error function, but at that point, the response was already sent … the response created by handle_error will be discarded." بدفهمی دوم: «این صف کار (Job queue) است.» با Process از بین میرود و Retry ندارد.
تعریف: FastAPI: "You can define background tasks to be run after returning a response." در قطعهکد create_order، تابع send_confirmation را اضافه میکند؛ گزارش واقعی confirmation sent for order 2 پس از 201 ظاهر میشود؛ test_201_with_location_and_background_task.
1 POST /orders -> 201 sent (Location: /orders/2)
2 then: send_confirmation(2) -> INFO [rid] shop: confirmation sent for order 2
3 an exception here -> logged by the 500 path, client unaffectedسناریوی واقعی: ایمیل تشکر؛ ارسال webhook به چند URL؛ حذف فایل موقت پس از FileResponse.
| نیاز | ابزار |
|---|---|
| کار کوچک، در حد تلاش ممکن، پس از پاسخ | BackgroundTasks |
| Retry، ماندگاری و زمانبندی | Job queue؛ Celery، ARQ، RQ یا Dramatiq |
| کار وابسته به Connection کارخواه، مانند جریان LLM | خود Generator جریان |
اصلاح / روش استفاده: Task کوتاه و Idempotent باشد. کاری که حتماً باید انجام شود در صف قرار میگیرد. شرح کامل: کارهای پسزمینه، Caching و APIهای خارجی.
سازوکار (Mechanics)
عبور یک درخواست از پشته، در موفقیت و شکست (One request through the stack, success and failure) مهم
FastAPI 0.128.8 پشته را در FastAPI.build_middleware_stack میسازد؛ کد ذخیره شده است. ابتدا ServerErrorMiddleware(handler=<your Exception/500 handler>, debug=debug)، سپس همهٔ Middlewareهای کاربر؛ آخرین مورد افزودهشده بیرونیترین است: "The last middleware added is the outermost, and the first is the innermost". متد add_middleware در Starlette، self.user_middleware.insert(0, ...) را اجرا میکند. بعد ExceptionMiddleware(handlers=<every other handler>, debug=debug)، سپس AsyncExitStackMiddleware در FastAPI که Dependencyهای yield را میبندد، و در نهایت router قرار میگیرد. هر APIRoute نیز فراخوانی خود را در wrap_app_handling_exceptions میپیچد؛ به همین دلیل Traceback خطای مدیریتشده دو بار starlette/_exception_handler.py را نشان میدهد.
POST /orders (409) and GET /boom (500), snippet app (real)
1 Uvicorn await app(scope, receive, send)
2 ServerErrorMiddleware try: await app(scope, receive, _send) (tracks response_started)
3 RequestIdMiddleware request_id_var.set(...); wraps send to add X-Request-ID
4 ExceptionMiddleware wrap_app_handling_exceptions(...)
5 AsyncExitStack, Router, APIRoute -> create_order() in the thread pool (def)
6a raise OutOfStock -> lookup handlers by MRO -> domain_error_handler -> JSONResponse 409
7a response sent through RequestIdMiddleware's send (gets X-Request-ID) -> Uvicorn: 409 Conflict
6b raise RuntimeError -> no handler -> propagates out of ExceptionMiddleware and RequestIdMiddleware
7b ServerErrorMiddleware: unhandled_handler -> 500 via the *outer* send (no middleware header) -> raise exc
8b Uvicorn: access log 500, then "ERROR: Exception in ASGI application" + tracebackException handler چگونه انتخاب میشود؟ (How an Exception handler is chosen) تکمیلی
تابع _lookup_exception_handler در Starlette، type(exc).__mro__ را پیمایش میکند و اولین کلاس موجود در جدول Exception handler را برمیگرداند. برای HTTPException ابتدا کلید عددی وضعیت امتحان میشود. همهٔ این نتیجهها در تست واقعی دیده شدهاند: کلید 404 خطای router را میگیرد؛ Exception handler مربوط به DomainError، FlashSaleSoldOut(OutOfStock) را میگیرد؛ Exception handler مربوط به fastapi.HTTPException کلاس HTTPException در Starlette را از router نمیگیرد. اینجا هرگز Exception انتخاب نمیشود، چون FastAPI آن را به ServerErrorMiddleware منتقل کرده است.
| Exception ایجادشده | جدول بررسیشده | ترتیب |
|---|---|---|
HTTPException(status_code=404) | ExceptionMiddleware | کلید 404، سپس MRO کلاس |
OutOfStock | ExceptionMiddleware | OutOfStock، DomainError، Exception که موجود نیست، BaseException |
RequestValidationError | ExceptionMiddleware | MRO آن؛ FastAPI پیشفرض نصب میکند |
RuntimeError | هیچ Exception handler در ExceptionMiddleware | سپس Exception handler در ServerErrorMiddleware |
| Exception داخل Exception handler | — | سپس ServerErrorMiddleware |
جریان چگونه اجرا میشود؟ (How a stream runs) تکمیلی
StreamingResponse.__call__ مقدار scope["asgi"]["spec_version"] را میخواند. برای سرور پایینتر از 2.4، مثل Uvicorn 0.39.0 که "2.3" میفرستد، یک Task group با stream_response(send) و listen_for_disconnect(receive) میسازد؛ هرکدام زودتر تمام شود دیگری را لغو میکند. برای سرور 2.4+ فقط ارسال جریان انجام میشود و OSError هنگام ارسال به ClientDisconnect تبدیل میشود. Iterator همگام در iterate_in_threadpool پیچیده میشود تا هر next() در نخ Worker اجرا شود. send در Uvicorn پس از Disconnect پیام بدنه را کنار میگذارد و هنگام توقف نوشتن منتظر flow.drain() میماند. از FastAPI 0.118.0 کد خروج Dependencyهای yield پس از ارسال پاسخ اجرا میشود؛ بنابراین Session پایگاه داده تا پایان استفادهٔ جریان باز میماند؛ تزریق وابستگی.
| نسخهٔ ASGI سرور | تشخیص Disconnect | اثر روی Generator |
|---|---|---|
| 2.3؛ Uvicorn 0.39.0 | Task با نام listen_for_disconnect | CancelledError در await بعدی |
| 2.4+ | OSError در send | raise شدن ClientDisconnect از send |
| همه | await request.is_disconnected() خودتان | بازگشت زودهنگام به تصمیم شما |
متن دقیق خطا، هشدار و گزارش (Exact errors, warnings and log lines) حیاتی
همهٔ خطهای زیر در اجرای قطعهکدها چاپ شدهاند: FastAPI 0.128.8، Starlette 0.49.3، Pydantic 2.13.5، Uvicorn 0.39.0، sse-starlette 3.3.0، httpx 0.28.1 و curl روی macOS.
| محرک | وضعیت | خروجی دقیق |
|---|---|---|
| سفارش ناشناخته | 404 | {"type":"https://shop.example/problems/order-not-found","title":"Order not found","status":404,"instance":"/orders/99",...,"detail":"Order 99 does not exist.","order_id":99} |
PUT /orders/1 | 405 | allow: GET، "title":"Method Not Allowed" |
استفادهٔ دوباره از Idempotency-Key | 409 | "title":"Duplicate order","detail":"This Idempotency-Key was already used." |
GET /boom | 500 | "detail":"Unexpected error. Quote the request id." + x-request-id: lab-500 |
| Uvicorn پس از 500 | — | INFO: 127.0.0.1:59214 - "GET /boom HTTP/1.1" 500 Internal Server Error سپس ERROR: Exception in ASGI application |
| گزارش 500 برنامه | — | ERROR [lab-500] shop: unhandled RuntimeError on GET /boom + Traceback |
| خطای مدیریتنشده بدون Exception handler | 500 | Internal Server Error با text/plain; charset=utf-8 |
debug=True | 500 | Traceback (most recent call last): …؛ text/plain یا HTML با Accept: text/html |
return HTTPException(409, ...) بدون اعلان | 200 | {"status_code":409,"detail":"out of stock","headers":null} |
همان با -> Any | 500 | PydanticSerializationError: Unable to serialize unknown type: <class 'fastapi.exceptions.HTTPException'> در گزارش سرور |
| ناسازگاری مدل پاسخ | 500 | fastapi.exceptions.ResponseValidationError |
| باگ داخل Exception handler | 500 | During handling of the above exception, another exception occurred: … TypeError |
DELETE با 204 | 204 | بدون بدنه و content-length؛ با content-type: application/json |
| خطا پس از اولین قطعه | 200 | خروج curl با 18؛ httpx با RemoteProtocolError: peer closed connection without sending complete message body (incomplete chunked read) |
Disconnect در /stream/ticks | — | INFO [7e8503…] shop: ticks cancelled after 18 chunks (client disconnected) |
| Headerهای پاسخ جریانی | 200 | transfer-encoding: chunked، بدون content-length |
FileResponse و Range: bytes=0-7 | 206 | content-range: bytes 0-7/193 |
StaticFiles و If-None-Match | 304 | etag: "135ff096b8253f9d131ad581821d13db"، بدون بدنه |
حل مسائل رایج (Solving the classic problems)
| باگ | نشانه | اصلاح | هزینه |
|---|---|---|---|
| خطا بهشکل مقدار بازگشتی | شکست با 200؛ Cache خطا را ذخیره میکند | raise و یک بار نگاشت | بازآرایی کوچک |
return HTTPException(...) | 200 با فیلدهای خطا یا 500 | raise | یک واژه |
except Exception کلی در Route | باگ 400 میشود و پیام افشا میشود | حذف؛ مدیریت در گردش 500 | کد کمتر |
Exception handler روی fastapi.HTTPException | قالب متفاوت 404/405 در router | ثبت روی کلاس Starlette | یک import |
debug=True بیرون لپتاپ | Traceback و رازها در بدنه | پیشفرض False در تنظیمات و تست | Config |
نبود Exception handler برای Exception | 500 با text/plain و بدون Request id | Problem عمومی و یک بار ثبت گزارش | 15 خط |
| انتظار افزودن Header به 500 توسط Middleware | نبود X-Request-ID روی خطا | تنظیم در Exception handler مربوط به 500 | 1 خط |
استفاده از HTTPException برای خطای Domain در سرویس | سرویس FastAPI را import میکند؛ CLI و Worker خطای HTTP میگیرند | کلاس Domain و جدول نگاشت | یک ماژول |
رسیدن IntegrityError خام به مرز | 500 برای مورد تکراری | تبدیل در store؛ raise DuplicateOrder from exc | چند خط |
نبود خطا در /docs | کارخواه خطای نوعدار ندارد | responses= با مدل خطا | یک dict |
| Streaming ظاهری؛ اول list | جهش حافظه و تأخیر اولین بایت | تولید داخل Generator | بازسازی ساختار |
Async generator بدون await | لغونشدن و توقف حلقه | await برای هر عضو یا Generator همگام | کم |
| نبود پاکسازی در Disconnect | ادامهٔ Upstream و هزینهٔ LLM | try/finally + aclose() | کم |
| SSE پشت Nginx در پایان میرسد | جریان بافرشده | X-Accel-Buffering: no و ping | Header |
SSE بدون id | تکرار یا گمشدن رویداد پس از وصل مجدد | id: + Last-Event-ID | طراحی |
یک محل برای هر خطا (One place for every error)
در برنامهٔ پس از اصلاح دقیقاً یک ماژول وضعیت HTTP شکستها را میداند: app/problems.py. Route خطا را raise میکند یا اجازه میدهد store این کار را بکند؛ store نتیجهٔ SQL را تبدیل میکند و Exception handler، Exception را. برای افزودن شکست جدید یک کلاس در domain.py، یک ردیف در DOMAIN_STATUS و یک تست لازم است. همین ماژول میان routerهای متعدد مشترک است و App factory آن را ثبت میکند؛ APIRouter و ساختار پروژه.
پیدا کردن هر 500 از گزارش کاربر (Finding any 500 from a user's report)
شناسهٔ درخواست (Request id) هم در ورودی و هم خروجی حضور دارد: Middleware آن را میپذیرد یا میسازد، پالایهٔ گزارش روی هر رکورد میگذارد و Exception handler مربوط به 500 آن را در بدنه و Header میدهد و Traceback را یک بار ثبت میکند. پشتیبانی شناسه را میگیرد؛ یک grep پشتهٔ خطا را پیدا میکند. آن را با X-Request-ID به سرویس پاییندست بفرستید یا از Trace id در OpenTelemetry استفاده کنید.
جریانهایی که در محیط واقعی دوام میآورند (Streams that survive the real world)
پیش از اولین بایت همهٔ بررسیها را انجام دهید؛ تنبل تولید کنید؛ در هر قطعه await و برای پاکسازی finally: داشته باشید. برای SSE، X-Accel-Buffering: no و Cache-Control: no-store بگذارید. فاصلهٔ کامنتهای Keep-alive (Keep-alive comments) از همهٔ مهلتهای بیکاری بین راه کمتر باشد. رویداد قابل بازپخش (Replay) باید id: داشته باشد. قاببندی را با TestClient و Disconnect و Back-pressure را روی Uvicorn واقعی تست کنید؛ مانند test_live.py قطعهکد.
انتخاب (Choosing)
| وضعیت | انتخاب | روش تکمیلی | دلیل |
|---|---|---|---|
| خواندن معمولی JSON | مدل با -> OrderOut | response_model_exclude_none برای خروجی کمفیلد | سریع و مستند |
| بازگرداندن ردیف خام | response_model=OrderOut | مدل خروجی جدا | پالایش |
| ردشدن بهدلیل قاعدهٔ کسبوکار | خطای Domain به 409/404/422 | جدول نگاشت | سرویس بدون HTTP میماند |
| احراز هویت / متد / اندازه | HTTPException با Header | Dependency | نتیجهٔ سطح HTTP |
| باگ | اجازهٔ raise | Exception handler مربوط به Exception و Request id | یک خط گزارش |
| ایجاد شد | 201 + Location | بازگرداندن منبع | RFC 9110 |
| حذف شد | 204 | 404 برای نبود منبع | بدون محتوا |
| خواندن قابل Cache | ETag + 304 | Cache-Control | صرفهجویی پهنای باند |
| بدنهٔ غیر JSON | response_class=HTMLResponse/PlainTextResponse | قالب برای HTML | Media type درست |
| فایل روی دیسک | FileResponse | پشتیبانی داخلی Range | Validator و 206 |
| بدنهٔ بزرگ تولیدی | StreamingResponse | Generator همگام برای منبع Blocking | حافظهٔ محدود |
| رویداد سرور به مرورگر | SSE با fastapi.sse 0.135+ یا sse-starlette | id، ping و Header پراکسی | اتصال مجدد خودکار |
| دوطرفه با تأخیر کم | WebSocket | ارتباط بلادرنگ | ارتباط تمامدوطرفه |
| توکن LLM | SSE روی POST | بستن Upstream هنگام Disconnect | هزینه |
| فایل ایستا در برنامهٔ کوچک | Mount با StaticFiles | زیرکلاس برای Cache-Control | سادگی |
| فایل ایستا با ترافیک واقعی | Nginx یا CDN | نام دارای اثرانگشت | آزادشدن Worker |
| کار کوچک پس از پاسخ | BackgroundTasks | Idempotent | سادگی |
| کار الزامی | صف | Retry | ماندگاری |
انتخاب شیوهٔ انتقال جریان (Which streaming transport)
| نیاز | جریان ساده | JSON Lines | SSE | WebSocket |
|---|---|---|---|---|
| API مرورگر | fetch و reader | fetch و شکستن خطها | EventSource | WebSocket |
| اتصال مجدد و ادامهٔ خودکار | خیر | خیر | بله؛ retry و Last-Event-ID | خودتان میسازید |
| پیام کارخواه به سرور | خیر | خیر | خیر؛ درخواست تازه لازم است | بله |
| رویداد نوعدار | خیر | یک JSON در هر خط | نام event: | پروتکل خودتان |
| سازگاری با پراکسی | خوب | خوب | خوب با Headerهای لازم | نیازمند پشتیبانی upgrade |
| پشتیبانی FastAPI | StreamingResponse | 0.134.0+ با yield | 0.135.0+ یا sse-starlette | @app.websocket |
در معماری: از یک پردازه تا سیستم توزیعشده (In architecture: from a single process to a distributed system)
یکپارچه: یک پردازه و یک پایگاه داده (Monolith)
یک app، یک problems.py، یک جدول نگاشت و یک Middleware مربوط به Request id کافی است. قطعهکد همین شکل را دارد: SQLite جای PostgreSQL نشسته، store نتیجهٔ خالی و IntegrityError را به خطای Domain تبدیل میکند، StaticFiles رابط مدیریت کوچک را سرو میکند و Endpoint مربوط به SSE از همان Process وضعیت سفارش را به صفحهٔ پیگیری میفرستد. مثال فروشگاه: POST /orders یا 201 میدهد یا Problem با 409؛ صفحهٔ پیگیری مشترک /sse/orders است و پس از اختلال شبکه با Last-Event-ID ادامه میدهد.
یکپارچهٔ ماژولار و چند پایگاه داده (Modular monolith)
هر ماژول، مثل سفارش، پرداخت و کاتالوگ، کلاس خطای Domain خودش را دارد. لایهٔ HTTP مشترک مالک قالب پاسخ است و کلاس پایهٔ هر ماژول، مانند OrdersError و PaymentsError، را از طریق تابع ثبت همان ماژول نگاشت میکند. URIهای type فضای نام ماژول را دارند؛ مثل .../problems/orders/out-of-stock. پایگاه دادهٔ دوم، مثل Redis برای Session یا index جستوجو، تبدیل خطای خودش را در آداپتور (Adapter) دارد؛ پایان مهلت Redis یک خطای Dependency شبیه PaymentProviderDown با 503 است، نه 500. Router نمیتواند Exception handler ثبت کند؛ APIRouter، exception_handler ندارد. بنابراین مرز ماژول در کلاسها بیان میشود، نه در routerها.
ریزسرویسها (Microservices)
خطا از شبکه عبور میکند و هر گام باید آن را آگاهانه تبدیل کند. مثال: POST /checkout روی سرویس سفارش، سپس POST http://payments/charges با X-Request-ID و Idempotency-Key، سپس پاسخ 402 Problem با card-declined از پرداخت. سرویس سفارش آن را به 409 خودش با payment-declined تبدیل میکند. پایان مهلت پرداخت 503 همراه Retry-After و 500 پرداخت، 502 سرویس سفارش میشود. کلاس Exception، Traceback و URIهای type سرویس دیگر از این مرز عبور معنایی ندارند؛ آنها را کورکورانه منتقل نکنید. جریان درخواست هم خودبهخود حفظ نمیشود؛ اگر جریان کارخواه از دو سرویس میگذرد، هر گام باید جریانی باشد و بافر نکند. پوشش مشترک RFC 9457 در سرویسهای Go و Python، کارخواه و Gateway را سادهتر میکند. طراحی Idempotency: تکرارپذیری API.
دادهٔ توزیعشده: Replica، Cache، پایگاه دادهٔ Sharded و چند منطقه (Distributed data)
ETag و 304 با نمونههای خواندن (Replica) تعامل دارند: ETag محاسبهشده روی Replica عقبمانده میتواند کارخواه را بهاشتباه بهروز نشان دهد. Validator را از ستون نسخهای بسازید که همراه ردیف جابهجا میشود، یا درخواست شرطی را از پایگاه اصلی (Primary) بخوانید. Cacheهای CDN، Nginx و Redis مشترک هرگز نباید بدنهٔ خطای دارای دادهٔ شخصی یا جریان رویداد را ذخیره کنند. روی این خطاها و جریانها Cache-Control: no-store بگذارید؛ no-cache فقط وقتی مناسب است که ذخیره مجاز باشد ولی هر استفادهٔ دوباره بازاعتبارسنجی شود، مثل index.html. SSE روی چند سرور به منبع رویداد مشترک نیاز دارد: Redis pub/sub، فرمان LISTEN/NOTIFY در Postgres یا Kafka. اتصال مجدد دارای Last-Event-ID باید بتواند روی هر Replica فرود بیاید و از گزارش ماندگار ادامه دهد، نه حافظهٔ یک Process. نرخ خطا برای هر URI در type سنجهٔ طبیعی هدف سطح خدمت (SLO) میان مناطق است. الگوهای Fan-out در ارتباط بلادرنگ و Cache در Caching آمدهاند.
روند مقیاسگیری: ۱×، ۱۰×، ۱۰۰× (Scaling path)
| بار | چه عوض میشود؟ | کار عملی |
|---|---|---|
| 1×؛ یک Process | پیشفرضها خوب به نظر میرسند | یک ماژول problems، Request id، بدون debug، مدل پاسخ، FileResponse و چند کارخواه SSE در app |
| 10×؛ Worker/Replica پشت Load balancer | جریان Connection نگه میدارد؛ وضعیت SSE هر Process متفاوت میشود؛ فایل ایستا با API رقابت میکند | Nginx یا CDN برای فایل؛ رویداد از Redis/Postgres؛ ping کوتاهتر از مهلت LB؛ --limit-concurrency؛ داشبورد خطا بر اساس type |
| 100×؛ سرویسهای زیاد و Connection طولانی | دهها هزار جریان باز، طوفان خطا و اتصال مجدد | Gateway ویژهٔ SSE/WebSocket؛ retry: با پراکندگی زمانی؛ Last-Event-ID از گزارش ماندگار؛ نوع Problem بهعنوان قرارداد؛ دفع بار با 503 و Retry-After؛ Load Shedding |
آزمایشگاه (Lab)
همهٔ فرمانها از docs/snippets/python/exception-handling-responses/ اجرا میشوند؛ محیط مجازی بیرون repo است. خروجیهای «واقعی» روی CPython 3.9.6 در macOS با نسخههای ثابت تولید و در pipeline/sources/exception-handling-responses/runs/ ذخیره شدهاند.
۱. نصب و اجرای تستها؛ واقعی
python3 -m venv /tmp/ehr-venv && /tmp/ehr-venv/bin/pip install '.[test]'
PYTHONDONTWRITEBYTECODE=1 /tmp/ehr-venv/bin/python -m pytest -s
# real: see runs/pytest-fresh-install.txt
# produced while the client read nothing: 18/512 chunks (1152 KiB); total received 32772 KiB
# after disconnect: ['ticks: cancelled after 3', 'ticks: cleanup']
# 50 passed۲. عبور خطا از Exception handlerها؛ واقعی
/tmp/ehr-venv/bin/uvicorn app.main:app --port 18921 # the venv from step 1 (or activate it first)
curl -si localhost:18921/orders/99 # 404 application/problem+json, type .../order-not-found
curl -si -X PUT localhost:18921/orders/1 # 405, allow: GET, title "Method Not Allowed"
curl -si -X POST localhost:18921/orders -H 'content-type: application/json' \
-H 'Idempotency-Key: lab-1' -d '{"sku":"BOOK-1","qty":2}' # 201, location: /orders/2
# same command again # 409 duplicate-order
curl -si -X DELETE localhost:18921/orders/2 # 204, no body۳. گردش 500 و گزارشها؛ واقعی
curl -si localhost:18921/boom -H 'X-Request-ID: lab-500'
# HTTP/1.1 500 Internal Server Error / x-request-id: lab-500 / content-type: application/problem+json
# {"type":"about:blank","title":"Internal Server Error","status":500,"instance":"/boom","request_id":"lab-500",...}
# server log:
# ERROR [lab-500] shop: unhandled RuntimeError on GET /boom (+ traceback)
# INFO: 127.0.0.1:59214 - "GET /boom HTTP/1.1" 500 Internal Server Error
# ERROR: Exception in ASGI application (+ traceback: the re-raise)سپس در یک کپی آزمایشی با FastAPI(debug=True) دوباره اجرا و درخواست را تکرار کنید. بدنه به Traceback شامل hunter2 تبدیل میشود؛ در test_before.py بررسی شده است.
۴. جریان، SSE و قطع اتصال؛ واقعی
curl -si "localhost:18921/stream/ticks?n=3" # transfer-encoding: chunked; tick 0..2
curl -sN -i "localhost:18921/sse/orders?idle=0.2&ping=0.1"
# : stream opened / retry: 5000 / event: order id: 0..2 / : keep-alive (x2) / event: end
curl -sN -H 'Last-Event-ID: 1' localhost:18921/sse/orders # only id: 2 (test_last_event_id_resumes)
curl -sN localhost:18921/sse/lib | cat -v # sse-starlette: lines end in ^M (\r\n)
curl -sN --max-time 0.2 "localhost:18921/stream/ticks?n=10000&delay=0.01"
# server log: INFO [7e8503…] shop: ticks cancelled after 18 chunks (client disconnected)۵. Exception در میانهٔ جریان؛ واقعی
/tmp/ehr-venv/bin/uvicorn app.midstream:app --port 18922 # app/midstream.py: yields "part 1", then raises
curl -si localhost:18922/s # 200 ... part 1 (curl exit code 18)
/tmp/ehr-venv/bin/python -c "import httpx; httpx.get('http://127.0.0.1:18922/s')"
# httpx.RemoteProtocolError: peer closed connection without sending complete message body (incomplete chunked read)۶. پشت Nginx؛ مورد انتظار، اجرا نشده
# nginx.conf (no Nginx on the build machine: expected behaviour from the Nginx docs)
location /sse/ { proxy_pass http://127.0.0.1:18921; proxy_http_version 1.1; }
# 1) /sse/orders with X-Accel-Buffering: no -> events arrive one by one
# 2) remove the header in a scratch copy -> events arrive together when the stream ends (proxy_buffering on)
# 3) /sse/orders?idle=90&ping=0 (silent 90 s; accepted by the app, real: 200)
# -> connection closed after proxy_read_timeout (60s default)
# 4) /sse/orders?idle=90&ping=15 -> stays open: each comment resets the 60 s read timerبرای توسعهدهندهٔ PHP/Laravel (For PHP/Laravel developers)
Laravel همان تفکیک دولایه را با نامهای دیگر دارد. در Laravel 13 تنظیم خطا با ->withExceptions() در bootstrap/app.php انجام میشود و جای کلاس App\Exceptions\Handler را گرفته است؛ مستندات Laravel 10.x میگفتند: "All exceptions are handled by the App\Exceptions\Handler class". متد $exceptions->report(...) نحوهٔ ثبت خطا و $exceptions->render(...) تبدیل آن به پاسخ را تعیین میکند. callback اختصاصی report جای گزارش پیشفرض را نمیگیرد: "Laravel will still log the exception using the default logging configuration"؛ مگر ->stop() بزنید یا false برگردانید. این همان تفکیک Logging در Exception handler مربوط به 500 و بازگرداندن بدنه از Exception handler در FastAPI است. Laravel اجازه میدهد خود کلاس Exception هر دو را داشته باشد: "you may define report and render methods directly on your application's exceptions. When these methods exist, they will automatically be called by the framework". این نزدیکترین معادل DomainError بهاضافهٔ جدول نگاشت در یک کلاس است. abort(404) معادل raise HTTPException(404) است. findOrFail با ModelNotFoundException مانند OrderNotFound قطعهکد عمل میکند؛ مستندات Eloquent: "If the ModelNotFoundException is not caught, a 404 HTTP response is automatically sent back to the client". قاعدهٔ Debug یکسان است: "In your production environment, the value of APP_DEBUG should always be false." انتخاب HTML یا JSON در Laravel، "based on the Accept header of the request" است و shouldRenderJsonWhen آن را تغییر میدهد. FastAPI تا وقتی خلافش را نگویید JSON میدهد؛ فقط صفحهٔ Debug به Accept نگاه میکند. در پاسخها، response()->download() و response()->file() معادل FileResponse با attachment و inline هستند. response()->stream() همان StreamingResponse است و مستندات Laravel همان Header را میفرستند: ['X-Accel-Buffering' => 'no']. همچنین "if the closure you provide to the stream method returns a Generator, Laravel will automatically flush the output buffer between strings returned by the generator, as well as disable Nginx output buffering". متد response()->streamJson() جریان JSON است و response()->eventStream()، "may be used to return a server-sent events (SSE) streamed response using the text/event-stream content type"؛ برای رویداد نامدار StreamedEvent دارد. تفاوت بزرگ مدل پردازه (Process model) است: طبق راهنمای PHP، PHP-FPM از مجموعهٔ Processهای فرزند استفاده میکند که pm.max_children سقف تعدادشان است. هر جریان باز یکی را تا پایان اشغال میکند. جریان FastAPI یک همروال (Coroutine) معلق روی Event loop است؛ بنابراین کارخواه SSE بیشتر حافظه میخواهد، نه Process بیشتر.
// bootstrap/app.php (Laravel 13): the mapping layer, like app/problems.py
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->render(function (OutOfStock $e, Request $request) { // OutOfStock -> 409 Problem
return response()->json([
'type' => 'https://shop.example/problems/out-of-stock', 'title' => 'Not enough stock',
'status' => 409, 'detail' => $e->getMessage(), 'instance' => $request->path(),
], 409, ['Content-Type' => 'application/problem+json']);
});
$exceptions->report(function (Throwable $e) { // log once, with context
Log::error($e->getMessage(), ['request_id' => request()->header('X-Request-ID')]);
})->stop(); // without stop(): logged twice
})
// routes/api.php: streaming and SSE, like app/streaming.py
Route::get('/export/orders.csv', fn () => response()->streamDownload(function () {
foreach (Order::lazy() as $o) { echo "{$o->id},{$o->sku},{$o->qty}\n"; } // sync generator in FastAPI
}, 'orders.csv', ['Content-Type' => 'text/csv']));
Route::get('/sse/orders', fn () => response()->eventStream(function () {
foreach (OrderStatus::forOrder(1) as $s) {
yield new StreamedEvent(event: 'order', data: $s->toJson()); // event: order / data: ...
}
}));| Laravel 13 | FastAPI |
|---|---|
->withExceptions() در bootstrap/app.php؛ قبلاً App\Exceptions\Handler | install_problem_handlers(app) |
$exceptions->render(fn (OutOfStock $e) => ...) | app.add_exception_handler(DomainError, handler) |
$exceptions->report(...)->stop() یا return false | یک بار log.exception(...) در Exception handler مربوط به Exception |
render() / report() روی Exception | جدول نگاشت با کلید کلاس |
abort(404) | raise HTTPException(404) |
findOrFail ← ModelNotFoundException ← 404 | Store.get ← OrderNotFound ← 404 |
APP_DEBUG=false | FastAPI(debug=False) |
shouldRenderJsonWhen | همیشه JSON در Exception handlerهای شما |
response()->json($data, 201)->header('Location', ...) | status_code=201 + response.headers["Location"] |
->cookie(...) / تابع کمکی cookie() | response.set_cookie(...) |
response()->download($path, $name) | FileResponse(path, filename=name) |
response()->stream(fn () => ..., 200, ['X-Accel-Buffering' => 'no']) | StreamingResponse(gen(), headers={"X-Accel-Buffering": "no"}) |
response()->streamJson([...]) | JSON Lines با yield از 0.134.0+ |
response()->eventStream(...) + StreamedEvent | fastapi.sse.EventSourceResponse از 0.135.0+ یا sse-starlette |
public/ با Nginx | Mount با StaticFiles یا Nginx/CDN |
کار صفشده با dispatch() | صف واقعی؛ BackgroundTasks برای کار کوچک پس از پاسخ |
زاویهٔ Go (The Go angle)
Go برای شکست مورد انتظار Exception ندارد؛ تابع مقدار error برمیگرداند و مرز HTTP وضعیت را تعیین میکند. نوشتهٔ Go 1.13 ابزارهای همتای جستوجوی Exception handler را معرفی میکند: "In Go 1.13, the fmt.Errorf function supports a new %w verb. When this verb is present, the error returned by fmt.Errorf will have an Unwrap method returning the argument of %w". همچنین "The errors.Is function compares an error to a value" در سراسر زنجیره. پس store میتواند fmt.Errorf("get order %d: %w", id, ErrOrderNotFound) بدهد و Exception handler هنوز errors.Is(err, ErrOrderNotFound) را بپرسد. این همان پیمایش MRO قطعهکد است، ولی روی زنجیرهٔ پیچیدن خطا (Error wrapping)، نه سلسلهمراتب کلاس. panic همتای خطای مدیریتنشده است؛ سرور net/http آن را برای هر اتصال (Connection) بازیابی و با http: panic serving %v: %v و پشته ثبت میکند؛ کد server.go. این همتای raise دوباره (Re-raise)ٔ ServerErrorMiddleware است و Middleware بازیابی بدنهٔ 500 را مینویسد. Streaming صریح است: روی ResponseWriter بنویسید و Flush() بزنید؛ رابط http.Flusher میگوید: "Flush sends any buffered data to the client". راه دیگر http.NewResponseController(w).Flush() است که در Go 1.20 بهعنوان "a clearer, more discoverable way to add per-handler controls" اضافه شد. برای درخواست ورودی، "the context is canceled when the client's connection closes"؛ از request.go. این همان request.is_disconnected() بهاضافهٔ لغو در یک مقدار است. تابع http.ServeContent، "handles Range requests properly, sets the MIME type, and handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since, and If-Range requests"؛ از fs.go. فصلهای مرتبط: خطا، panic، recover و defer و سرور و کارخواه net/http.
// Go 1.22+: the mapping table and an SSE stream, like app/problems.py and app/streaming.py
var (
ErrOrderNotFound = errors.New("order not found")
ErrOutOfStock = errors.New("out of stock")
)
func writeProblem(w http.ResponseWriter, r *http.Request, err error) {
status, slug := http.StatusInternalServerError, "" // default: the 500 path
switch {
case errors.Is(err, ErrOrderNotFound): // walks the %w chain, like the MRO lookup
status, slug = http.StatusNotFound, "order-not-found"
case errors.Is(err, ErrOutOfStock):
status, slug = http.StatusConflict, "out-of-stock"
default:
slog.Error("unhandled", "err", err, "request_id", r.Header.Get("X-Request-ID")) // log once
}
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]any{"type": "https://shop.example/problems/" + slug,
"title": http.StatusText(status), "status": status, "instance": r.URL.Path})
}
func orderEvents(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Accel-Buffering", "no")
rc := http.NewResponseController(w)
for seq, status := range []string{"paid", "packed", "shipped"} {
select {
case <-r.Context().Done(): // client disconnect: the context is cancelled
return
default:
}
fmt.Fprintf(w, "event: order\nid: %d\ndata: {\"status\":%q}\n\n", seq, status)
rc.Flush() // like each yield in StreamingResponse
}
}| موضوع | FastAPI | Go net/http |
|---|---|---|
| شکست مورد انتظار | raise OrderNotFound | return fmt.Errorf("...: %w", ErrOrderNotFound) |
| تطبیق | جستوجوی Exception handler در MRO کلاس | errors.Is / errors.As در زنجیرهٔ %w |
| نگاشت به HTTP | یک Exception handler و جدول | یک تابع writeProblem |
| شکست غیرمنتظره | Exception، سپس ServerErrorMiddleware، سپس 500 و raise دوباره (Re-raise) | panic؛ بازیابی سرور و ثبت http: panic serving ...؛ Middleware بازیابی 500 را مینویسد |
| Header خطا | HTTPException(headers=...) | w.Header().Set(...) پیش از WriteHeader |
| Streaming | StreamingResponse(generator) | Write + Flush |
| Disconnect | لغو و is_disconnected() | r.Context().Done() |
| Back-pressure | await send مولد را متوقف میکند | Write، goroutine را متوقف میکند |
| فایل ایستا | StaticFiles | http.FileServer(http.Dir(...)) |
| دانلود فایل | FileResponse با Range و ETag | http.ServeContent با Range، If-None-Match و If-Modified-Since |
بدفهمیهای رایج (Common misconceptions)
| باور | واقعیت |
|---|---|
Exception handler مربوط به Exception خطا را میبلعد | ServerErrorMiddleware بعد از 500 raise دوباره (Re-raise) میکند؛ Uvicorn ثبت و TestClient خطا را raise میکند |
return HTTPException(...) درست است | 200 با فیلدهای Exception یا 500 با -> Any؛ واقعی |
Exception handler مربوط به fastapi.HTTPException، 404 router را میگیرد | کلاس Starlette را ثبت کنید؛ کلاس FastAPI زیرکلاس است |
| Middleware روی هر پاسخ Header میگذارد | روی 500 ساختهشدهٔ ServerErrorMiddleware نمیگذارد؛ در Exception handler تنظیم کنید |
debug=True فقط پشته اضافه میکند | خط کد و پیام حاوی راز را میفرستد و Exception handler مربوط به 500 را کنار میگذارد |
| اتمام موجودی 400/422 است | درخواست معتبر را وضعیت فعلی رد کرده؛ 409 Conflict |
response_model و -> Model تعارض دارند | در حضور هر دو، response_model اولویت دارد |
204 یعنی {} | بدون بدنه؛ در FastAPI 0.128.8 هنوز content-type: application/json اضافه میشود؛ واقعی |
ORJSONResponse سریعترین راه است | از 0.131.0 منسوخ؛ مدل پاسخ در Rust سریالسازی میشود |
StreamingResponse(iter(big_list)) حافظه صرفهجویی میکند | list از قبل در حافظه است |
| کارخواه کند کل پاسخ را در سرور بافر میکند | await send مولد را متوقف میکند؛ 18 از 512 قطعه در آزمایش واقعی |
| Disconnect کار را فوری متوقف میکند | فقط در await بعدی؛ حلقهٔ CPU ادامه میدهد |
| خطای میانهٔ جریان 500 میدهد | وضعیت از قبل 200 است؛ بدنه ناقص میشود؛ کد خروج واقعی curl برابر 18 |
هر yield رویداد SSE است | فقط خط خالی رویداد را تحویل میدهد |
| SSE پشت Nginx همان رفتار محلی را دارد | proxy_buffering on آن را نگه میدارد؛ X-Accel-Buffering: no بفرستید |
StaticFiles سیاست Cache میگذارد | Validator و 304 دارد، Cache-Control ندارد |
| خطای Task پسزمینه به کارخواه میرسد | پاسخ قبلاً ارسال شده؛ خطا فقط ثبت میشود |
برگهٔ تقلب (Cheat sheet)
| موضوع | چیزی که باید حفظ باشید |
|---|---|
| raise کنید؛ return نکنید | raise HTTPException(404, detail=..., headers=...) |
| کلاس مناسب ثبت | starlette.exceptions.HTTPException |
| خطای اختصاصی | کلاسهای Domain و یک Exception handler برای هر کلاس پایه با MRO |
| 500 | add_exception_handler(Exception, h) به ServerErrorMiddleware میرود؛ سپس raise دوباره (Re-raise) |
| Headerهای 500 | در Exception handler تنظیم میشوند؛ Middleware نمیتواند |
| Debug | بیرون لپتاپ False؛ Exception handler مربوط به 500 را دور میزند |
| قالب | RFC 9457، application/problem+json، type/title/status/detail/instance و عضو افزوده |
| نگاشت | سرویس معنای شکست را raise میکند؛ یک جدول وضعیت/type/عنوان را میدهد |
| گزارش | یک بار logger.exception با Request id از ContextVar |
| مستندات | responses={404: {"model": Problem}} |
| خروجی | -> Model یا response_model=؛ exclude_unset / exclude_none |
| وضعیت | 201 و Location، 204 بدون بدنه، 304 با همان Validatorها |
| کلاسها | HTMLResponse، PlainTextResponse، RedirectResponse با 307، FileResponse، StreamingResponse |
| جریان | Generator تنبل، await در هر قطعه، پاکسازی finally: و بررسی پیش از اولین بایت |
| SSE | text/event-stream، id/event/retry/data، خط خالی، : ping، Last-Event-ID |
| پراکسی | X-Accel-Buffering: no و Cache-Control: no-store؛ no-cache ذخیره و بازاعتبارسنجی میکند؛ فاصلهٔ ping کمتر از مهلت بیکاری |
| فایل ایستا | StaticFiles(html=True) زیر پیشوند؛ Cache-Control با شما؛ در مقیاس بالا CDN |
خودآزمایی: پرسش و پاسخ (Self-check: questions & answers)
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا باید HTTPException را raise کنید و با return چه میشود؟ حیاتی
پاسخ
پاسخ: raise در هر عمق اجرای درخواست را متوقف میکند و Exception را به Exception handler میدهد تا وضعیت، detail و Headerها را ارسال کند. با return فقط یک شیء معمولی دارید: بدون اعلان نوع بازگشت، FastAPI ویژگیها را سریالسازی میکند و 200 با {"status_code":409,"detail":"out of stock","headers":null} میفرستد؛ با -> Any سریالسازی شکست میخورد و کارخواه 500 میگیرد. هر دو در اجرا دیده شدهاند؛ HTTPException.
۲ — @app.exception_handler(HTTPException) را با import از fastapi ثبت کردهاید، اما URL اشتباه هنوز {"detail":"Not Found"} میدهد. چرا و راهحل چیست؟ حیاتی
پاسخ
پاسخ: router و StaticFiles کلاس والد، یعنی HTTPException در Starlette، را raise میکنند؛ Exception handler زیرکلاس FastAPI با والد تطبیق ندارد. Exception handler را برای starlette.exceptions.HTTPException ثبت کنید تا هم خطای شما و هم 404/405 router را بگیرد. باید exc.headers را نگه دارد؛ مثلاً allow در 405. تفاوت FastAPI و Starlette.
۳ — با raise شدن RuntimeError در Route و وجود Exception handler برای Exception دقیقاً چه رخ میدهد؟ حیاتی
پاسخ
پاسخ: ExceptionMiddleware Exception handler ندارد؛ خطا از همهٔ Middlewareهای کاربر عبور میکند و به بیرونیترین لایه، ServerErrorMiddleware، میرسد. آن لایه Exception handler شما را اجرا میکند، پاسخ را با send بیرونی میفرستد، بنابراین Middleware کاربر نمیتواند Header اضافه کند، و سپس raise دوباره (Re-raise) میکند. Uvicorn پیام Exception in ASGI application را با Traceback ثبت میکند؛ TestClient(app) خطا را در تست raise میکند مگر raise_server_exceptions=False باشد. Exception handler مربوط به Exception.
۴ — چگونه OrderNotFound و OutOfStock سرویس را بدون import کردن FastAPI در سرویس به HTTP نگاشت میکنید؟ حیاتی
پاسخ
پاسخ: سلسلهمراتب Domain با پایهٔ DomainError و زیرکلاسهای OrderNotFound و OutOfStock تعریف کنید و در سرویس یا store آنها را raise کنید. نتیجهٔ SQL همانجا تبدیل شود: ردیف خالی به OrderNotFound و IntegrityError به DuplicateOrder. یک Exception handler برای DomainError کلاس را در MRO و جدول وضعیت، URI مربوط به type و عنوان جستوجو کند: 404 برای نبودن و 409 Conflict برای تعارض وضعیت. زیرکلاس نگاشتنشده 500 میشود و ثبت میشود؛ نگاشت خطای Domain.
۵ — کارخواه CSV بزرگ را جریانی ولی خیلی کند میخواند. آیا سرور کل فایل را در حافظه بافر میکند؟ حیاتی
پاسخ
پاسخ: اگر Generator تنبل تولید کند، خیر. بعد از هر yield، await send(...) هست و Flow control در Uvicorn با pause_writing و سپس drain() آن را تا خالیشدن بافر سوکت متوقف میکند؛ Generator معلق میماند. در اندازهگیری، کارخواه نیمثانیه چیزی نخواند و تولیدکننده فقط ۱۸ قطعه از ۵۱۲ قطعهٔ ۶۴ KiB جلو رفت. ساختن list از قبل یا صف نامحدود میان تولیدکننده و فرستنده این خاصیت را از بین میبرد؛ Back-pressure.
۶ — بایتهای رویداد SSE با نوع order، شناسهٔ ۷ و دادهٔ JSON را بنویسید؛ مرورگر پس از قطع چگونه ادامه میدهد؟ مهم
پاسخ
پاسخ: event: order\nid: 7\ndata: {"status":"paid"}\n\n با Content-Type: text/event-stream؛ خط خالی رویداد را تحویل میدهد. EventSource آخرین id را نگه میدارد، بهاندازهٔ retry: صبر میکند و درخواست تازهای با Last-Event-ID: 7 میفرستد. سرور Header را میخواند و پس از رویداد ۷ ادامه میدهد؛ در آزمایش Last-Event-ID: 1 فقط رویداد ۲ را داد. SSE.
۷ — SSE محلی درست است ولی پشت Nginx رویدادها آخر کار میرسند و جریان ساکت پس از یک دقیقه میمیرد. چه عوض میکنید؟ مهم
پاسخ
پاسخ: پیشفرض Nginx، proxy_buffering on، پاسخ را بافر میکند؛ X-Accel-Buffering: no بفرستید یا در همان location بافر را غیرفعال کنید. proxy_read_timeout با پیشفرض ۶۰ ثانیه Connection بدون بایت میان خواندنها را میبندد؛ طبق توصیهٔ WHATWG تقریباً هر ۱۵ ثانیه توضیحی مثل : keep-alive بفرستید. Cache-Control: no-store هم لازم است تا جریان ذخیره نشود؛ no-cache ذخیره را مجاز میداند و فقط بازاعتبارسنجی را اجباری میکند. پراکسیها.
۸ — Endpoint جریانی رفتن کارخواه را چگونه میفهمد و Generator چه وظیفهای دارد؟ مهم
پاسخ
پاسخ: با Uvicorn 0.39.0 و ASGI 2.3، Starlette کنار جریان یک شنوندهٔ Disconnect اجرا میکند و با http.disconnect گروه Task را لغو میکند؛ Generator در await بعدی CancelledError میگیرد. بین قطعهها await request.is_disconnected() هم در دسترس است. Generator باید مرتب await کند، در finally: منابع مثل جریان Upstream و cursor را ببندد و CancelledError را raise دوباره (Re-raise) کند. خروجی واقعی ticks cancelled after 18 chunks (client disconnected) بود؛ قطع اتصال کارخواه.
۹ — اگر بعد از اولین قطعهٔ جریان Exception رخ دهد کارخواه چه میبیند و خطا را چگونه اعلام میکنید؟ مهم
پاسخ
پاسخ: وضعیت 200 و Headerها قبلاً ارسال شدهاند و هیچ Exception handler نمیتواند آنها را تغییر دهد؛ Connection بدون قطعهٔ پایانی بسته میشود. curl با کد خروج ۱۸ و httpx با RemoteProtocolError ... incomplete chunked read شکست میخورند. بررسیهایی را که کد وضعیت شکست میخواهند پیش از اولین yield انجام دهید و خطاهای بعدی را در خود جریان گزارش کنید؛ مثلاً SSE با event: error یا رکورد نهایی خطا در JSON Lines. خطای میانهٔ جریان.
۱۰ — response_model، اعلان بازگشت، response_model_exclude_unset و response_model_exclude_none چه میکنند و اولویت اعلان مدل با کدام است؟ مهم
پاسخ
پاسخ: هم response_model= و هم -> Model خروجی را Validation، پالایش و مستند میکنند؛ در حضور هر دو، response_model اولویت دارد. exclude_unset فیلد هرگز صریحاً تنظیمنشده، یعنی پیشفرضها، را حذف میکند؛ exclude_none فیلد با مقدار None را. در اجرا تنظیمات با فقط language به {"language":"fa"} رسید و سفارش با یادداشت null اصلاً کلید note نداشت. response_model.
۱۱ — پاسخهای 201، 204 و 304 چه بدنه و Headerهایی میخواهند و FastAPI چطور آنها را میسازد؟ تکمیلی
پاسخ
پاسخ: 201 Created معمولاً خود منبع و Header با نام Location دارد؛ با status_code=201 در دکوراتور و response.headers["Location"]. پاسخ 204 No Content بدنه ندارد؛ status_code=204 و بازگرداندن None، هرچند 0.128.8 هنوز content-type: application/json اضافه میکند. پاسخ 304 Not Modified هم بدنه ندارد ولی همان Validatorهای 200، یعنی ETag و Cache-Control، را دارد؛ هنگام تطبیق If-None-Match، Response(status_code=304, headers=...) برگردانید. کدهای وضعیت.
۱۲ — StaticFiles چه وقت مناسب است و چه چیزی را باید خودتان اضافه کنید؟ تکمیلی
پاسخ
پاسخ: برای توسعه و ابزار داخلی کوچک مناسب است؛ زیر پیشوندی مثل /app نصب کنید و برای index.html و 404.html، html=True بگذارید. ETag و Last-Modified و پاسخ 304 دارد ولی Cache-Control ندارد؛ آن را با زیرکلاس اضافه کنید: immutable برای نام دارای اثرانگشت و no-cache برای HTML. با ترافیک واقعی یا کاربر جهانی سرو فایل را به Nginx یا CDN بسپارید. StaticFiles.
واژهنامه (Glossary)
| اصطلاح | معنا |
|---|---|
HTTPException | Exception خطای HTTP در FastAPI با status_code، detail شامل هر JSON و headers |
starlette.exceptions.HTTPException | کلاس والد؛ detail رشته است؛ router و StaticFiles آن را raise میکنند |
detail | پیام یا محتوای خطای HTTPException؛ همچنین عضو RFC 9457 |
status_code | وضعیت HTTP پاسخ یا Exception |
| Header روی Exception (Headers on exceptions) | HTTPException(headers=...)؛ ارسال با پاسخ خطا، مثل WWW-Authenticate و Retry-After |
| کلاس خطای اختصاصی (Custom exception class) | زیرکلاس Exception خودتان برای شکست Domain |
exception_handler | دکوراتور ثبت (request, exc) -> Response برای کلاس یا کد وضعیت |
add_exception_handler | همان ثبت، با فراخوانی متد |
Exception handler مربوط به Exception | Exception handler مربوط به 500 که FastAPI به ServerErrorMiddleware میدهد |
ServerErrorMiddleware | بیرونیترین لایهٔ Starlette؛ پاسخ 500 یا Traceback حالت (Mode) Debug، سپس raise دوباره (Re-raise) |
ExceptionMiddleware | لایهٔ درونی اجرای همهٔ Exception handlerهای دیگر |
| raise دوباره (Re-raise) | ServerErrorMiddleware پس از پاسخ Exception را با raise دوباره (Re-raise) بالا میفرستد تا سرور ثبت کند |
| 500 Internal Server Error | "the server encountered an unexpected condition"؛ RFC 9110 |
| حالت اشکالزدایی (Debug mode) | FastAPI(debug=True)؛ Traceback در 500؛ هرگز در محیط عملیاتی |
RequestValidationError | ورودی با امضای تابع سازگار نیست؛ پیشفرض 422 |
ResponseValidationError | خروجی با مدل پاسخ سازگار نیست؛ 500 |
| 422 | Unprocessable Content؛ ورودی فهمیده شده ولی معتبر نیست |
| جزئیات مشکل (Problem Details) | قالب RFC 9457؛ type، title، status، detail، instance و عضوهای افزوده |
| RFC 9457 | استاندارد ژوئیهٔ ۲۰۲۳ برای Problem Details؛ جایگزین RFC 7807 |
application/problem+json | Media type بدنهٔ JSON در Problem Details |
| نگاشت خطای دامنه (Domain error mapping) | جدول کلاس Exception دامنه به وضعیت، type و عنوان |
OrderNotFound | خطای Domain قطعهکد برای نبود سفارش؛ 404 |
| 404 Not Found | منبع هدف بازنمایی جاری ندارد |
| 409 Conflict | درخواست با وضعیت فعلی منبع تعارض دارد |
| شناسهٔ درخواست (Request id) | شناسهٔ هر درخواست در گزارش، Header با نام X-Request-ID و بدنهٔ خطا |
ContextVar | متغیر مستقل هر Task از contextvars؛ حامل Request id |
پارامتر responses | آرگومان دکوراتور برای مستندکردن وضعیتهای اضافه در OpenAPI |
| مدل پاسخ خطا (Error response model) | مدل Pydantic مثل Problem در responses= |
response_model | آرگومان دکوراتور برای Validation، پالایش و مستندسازی خروجی |
| اعلان نوع بازگشت (Return type annotation) | -> Model؛ در نبود response_model مدل پاسخ میشود |
response_model_exclude_unset | حذف فیلدهایی که هرگز تنظیم نشدهاند |
response_model_exclude_none | حذف فیلدهای برابر None |
response_class | کلاس پاسخ Route؛ Media type در مستندات و روی شبکه |
JSONResponse | بدنهٔ JSON با json.dumps؛ کلاس پیشفرض بدون مدل |
ORJSONResponse | JSON با orjson؛ منسوخ از FastAPI 0.131.0 |
| orjson | کتابخانهٔ سریع JSON در Rust؛ 3.11.5 آخرین انتشار برای Python 3.9 |
PlainTextResponse / HTMLResponse | کلاس پاسخ متن و HTML |
RedirectResponse | Redirect با Location؛ پیشفرض 307 |
FileResponse | ارسال جریانی فایل با Content-Length، Last-Modified، ETag و Range |
Set-Cookie روی Response | response.set_cookie(...) روی پاسخ تزریقشده یا بازگشتی |
201 Created / Header با نام Location | منبع تازه ساخته شده؛ Location نشانی آن را میدهد |
| 204 No Content | موفقیت بدون بدنه |
| 304 Not Modified | درخواست شرطی؛ کپی کارخواه بهروز است |
ETag | Validator بازنمایی؛ مقایسه با If-None-Match |
StreamingResponse | بدنه از Generator یا Async generator؛ ارسال همزمان با تولید |
| مولد / مولد ناهمگام (Generator / async generator) | تابع def یا async def دارای yield؛ تولیدکنندهٔ جریان |
| کدگذاری انتقال قطعهای (Chunked transfer encoding) | قاببندی HTTP/1.1 برای بدنهٔ با طول نامعلوم؛ RFC 9112 بخش ۷٫۱ |
| فشار برگشتی (Back-pressure) | خوانندهٔ کند از طریق await send تولیدکننده را متوقف میکند |
| قطع اتصال کارخواه (Client disconnect) | کارخواه Connection را بسته؛ جریان لغو میشود |
request.is_disconnected | Coroutine گزارشدهندهٔ رفتن کارخواه |
| رویدادهای ارسالی سرور (Server-Sent Events) | جریان یکطرفهٔ رویداد روی HTTP؛ WHATWG HTML بخش ۹٫۲ |
text/event-stream | Media type مربوط به SSE |
| شناسه / تلاش دوبارهٔ رویداد (Event id / retry) | id: آخرین شناسه و retry: زمان اتصال مجدد بر حسب ms را تنظیم میکند |
Last-Event-ID | Header درخواست با آخرین شناسهٔ دریافتی مرورگر |
| sse-starlette | بستهٔ ثالث SSE با EventSourceResponse و ServerSentEvent |
EventSourceResponse | کلاس پاسخ SSE در sse-starlette یا fastapi.sse از 0.135.0+ |
| بافرکردن پراکسی (Proxy buffering) | پراکسی معکوس پاسخ را پیش از ارسال جمع میکند |
X-Accel-Buffering | Header پاسخ برای روشن یا خاموشکردن بافر Nginx در همان پاسخ |
| کامنتهای Keep-alive (Keep-alive comments) | خطهای دورهای : ... برای جلوگیری از بستهشدن جریان بیکار |
| جریان توکن LLM (LLM token streaming) | فرستادن Delta خروجی مدل به کارخواه در رویداد SSE |
StaticFiles | برنامهٔ Starlette برای سرو پوشه، نصبشده زیر یک Path |
mount | قراردادن برنامهٔ مستقل ASGI زیر پیشوند Path |
html=True | حالت (Mode) HTML در StaticFiles؛ index.html برای پوشه و 404.html برای نبود فایل |
Cache-Control فایل ایستا | immutable و max-age طولانی برای فایل دارای اثرانگشت؛ no-cache برای HTML |
| شبکهٔ توزیع محتوا (CDN) | Cacheهای لبه برای سرو فایل ایستا نزدیک کاربران |
BackgroundTasks | تابعهای اجراشده پس از پاسخ در همان Process |
X-Request-ID | Header قراردادی حامل Request id |
| Laravel Exception handler | تنظیم Exception در Laravel با withExceptions()، render و report |
render / report در Laravel | تبدیل Exception به پاسخ / ثبت آن |
پیچیدن خطای Go و errors.Is (Go error wrapping) | fmt.Errorf("...: %w", err) زنجیره میسازد؛ errors.Is Sentinel را در سراسر آن تطبیق میدهد |
منابع (References)
- FastAPI, "Handling Errors": https://fastapi.tiangolo.com/tutorial/handling-errors/
- FastAPI, "Response Model - Return Type": https://fastapi.tiangolo.com/tutorial/response-model/
- FastAPI, "Response Status Code": https://fastapi.tiangolo.com/tutorial/response-status-code/
- FastAPI, "Static Files": https://fastapi.tiangolo.com/tutorial/static-files/
- FastAPI, "Background Tasks": https://fastapi.tiangolo.com/tutorial/background-tasks/
- FastAPI, "Server-Sent Events (SSE)": https://fastapi.tiangolo.com/tutorial/server-sent-events/
- FastAPI, "Stream JSON Lines": https://fastapi.tiangolo.com/tutorial/stream-json-lines/
- FastAPI, "Request Files": https://fastapi.tiangolo.com/tutorial/request-files/
- FastAPI, "Middleware": https://fastapi.tiangolo.com/tutorial/middleware/
- FastAPI, "Additional Responses in OpenAPI": https://fastapi.tiangolo.com/advanced/additional-responses/
- FastAPI, "Additional Status Codes": https://fastapi.tiangolo.com/advanced/additional-status-codes/
- FastAPI, "Custom Response - HTML, Stream, File, others": https://fastapi.tiangolo.com/advanced/custom-response/
- FastAPI, "Return a Response Directly": https://fastapi.tiangolo.com/advanced/response-directly/
- FastAPI, "Response Headers": https://fastapi.tiangolo.com/advanced/response-headers/
- FastAPI, "Response Cookies": https://fastapi.tiangolo.com/advanced/response-cookies/
- FastAPI, "Response - Change Status Code": https://fastapi.tiangolo.com/advanced/response-change-status-code/
- FastAPI, "Stream Data": https://fastapi.tiangolo.com/advanced/stream-data/
- FastAPI, "Advanced Middleware": https://fastapi.tiangolo.com/advanced/middleware/
- FastAPI, "Lifespan Events": https://fastapi.tiangolo.com/advanced/events/
- FastAPI, "Advanced Dependencies": https://fastapi.tiangolo.com/advanced/advanced-dependencies/
- FastAPI reference, "Custom Response Classes": https://fastapi.tiangolo.com/reference/responses/
- FastAPI reference, "Exceptions": https://fastapi.tiangolo.com/reference/exceptions/
- FastAPI reference, "Static Files": https://fastapi.tiangolo.com/reference/staticfiles/
- FastAPI, "Release Notes": https://fastapi.tiangolo.com/release-notes/
- Starlette, "Responses": https://www.starlette.dev/responses/
- Starlette, "Exceptions": https://www.starlette.dev/exceptions/
- Starlette, "Middleware": https://www.starlette.dev/middleware/
- Starlette, "Requests": https://www.starlette.dev/requests/
- Starlette, "Static Files": https://www.starlette.dev/staticfiles/
- Starlette, "Release Notes": https://www.starlette.dev/release-notes/
- Uvicorn, "Settings": https://www.uvicorn.dev/settings/
- sse-starlette README: https://raw.githubusercontent.com/sysid/sse-starlette/main/README.md
- PyPI JSON, sse-starlette: https://pypi.org/pypi/sse-starlette/json
- PyPI JSON, orjson: https://pypi.org/pypi/orjson/json
- PyPI JSON, FastAPI: https://pypi.org/pypi/fastapi/json
- PyPI JSON, Starlette: https://pypi.org/pypi/starlette/json
- orjson README: https://raw.githubusercontent.com/ijl/orjson/master/README.md
- WHATWG HTML, "Server-sent events": https://html.spec.whatwg.org/multipage/server-sent-events.html
- MDN, "Using server-sent events": https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
- MDN, "Cache-Control": https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control
- MDN, "ETag": https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/`ETag`
- MDN, "Transfer-Encoding": https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Transfer-Encoding
- MDN, "304 Not Modified": https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/304
- RFC 9457, Problem Details for HTTP APIs: https://www.rfc-editor.org/rfc/rfc9457.txt
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110.txt
- RFC 9112, HTTP/1.1: https://www.rfc-editor.org/rfc/rfc9112.txt
- Nginx,
ngx_http_proxy_module: https://nginx.org/en/docs/http/ngx_http_proxy_module.html - Python,
logging: https://docs.python.org/3/library/logging.html - Python,
contextvars: https://docs.python.org/3/library/contextvars.html - AnyIO, "Streams": https://anyio.readthedocs.io/en/stable/streams.html
- SQLAlchemy 2.0, "Core Exceptions": https://docs.sqlalchemy.org/en/20/core/exceptions.html
- SQLAlchemy 2.0, "ORM API Features for Querying": https://docs.sqlalchemy.org/en/20/orm/queryguide/api.html
- SQLModel, "Read One Model with FastAPI": https://sqlmodel.tiangolo.com/tutorial/fastapi/read-one/
- Alembic, "Operation Reference": https://alembic.sqlalchemy.org/en/latest/ops.html
- Laravel 13.x, "Error Handling": https://laravel.com/docs/13.x/errors
- Laravel 13.x, "HTTP Responses": https://laravel.com/docs/13.x/responses
- Laravel 13.x, "File Storage": https://laravel.com/docs/13.x/filesystem
- Go blog, "Working with Errors in Go 1.13": https://go.dev/blog/go1.13-errors
- Go source,
net/http/server.go: https://go.dev/src/net/http/server.go - Go source,
net/http/request.go: https://go.dev/src/net/http/request.go - Go source,
net/http/responsecontroller.go: https://go.dev/src/net/http/responsecontroller.go - Go source,
net/http/fs.go: https://go.dev/src/net/http/fs.go - Go 1.20 release notes: https://go.dev/doc/go1.20
- Laravel 13.x, "Eloquent: Getting Started": https://laravel.com/docs/13.x/eloquent
- Laravel 10.x, "Error Handling" (the
App\Exceptions\Handlerera): https://laravel.com/docs/10.x/errors - PHP manual, "FastCGI Process Manager (FPM)" configuration: https://www.php.net/manual/en/install.fpm.configuration.php
- Go source,
errors/wrap.go: https://go.dev/src/errors/wrap.go