From 163e35c544b46214978c3bcce563d68d08b35b34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebasti=C3=A1n=20Ram=C3=ADrez?= Date: Fri, 27 Feb 2026 20:09:10 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20Tweak=20the=20docs=20text=20and?= =?UTF-8?q?=20example?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/en/docs/advanced/custom-response.md | 10 ++++++---- docs_src/custom_response/tutorial007_py310.py | 5 ++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/en/docs/advanced/custom-response.md b/docs/en/docs/advanced/custom-response.md index a919604bac..823ee5ff2c 100644 --- a/docs/en/docs/advanced/custom-response.md +++ b/docs/en/docs/advanced/custom-response.md @@ -167,13 +167,15 @@ You can also use the `status_code` parameter combined with the `response_class` Takes an async generator or a normal generator/iterator and streams the response body. -{* ../../docs_src/custom_response/tutorial007_py310.py hl[4,17] *} +{* ../../docs_src/custom_response/tutorial007_py310.py hl[3,16] *} -/// note +/// note | Technical Details + +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. -An `async` task can only be cancelled when it reaches an `await`. If there is no `await`, the generator can not be cancelled properly and may keep running even after cancellation is requested. +Since this small example does not need any `await` statements, we add an `await anyio.sleep(0)` to give the event loop a chance to handle cancellation. -Since this small example does not need any `await` statements, we add an `await asyncio.sleep(0)` to give the event loop a chance to handle cancellation. +This would be even more important with large or infinite streams. /// diff --git a/docs_src/custom_response/tutorial007_py310.py b/docs_src/custom_response/tutorial007_py310.py index 47db025cc6..f8dd9f895d 100644 --- a/docs_src/custom_response/tutorial007_py310.py +++ b/docs_src/custom_response/tutorial007_py310.py @@ -1,5 +1,4 @@ -import asyncio - +import anyio from fastapi import FastAPI from fastapi.responses import StreamingResponse @@ -9,7 +8,7 @@ app = FastAPI() async def fake_video_streamer(): for i in range(10): yield b"some fake video bytes" - await asyncio.sleep(0) + await anyio.sleep(0) @app.get("/")