Browse Source

fix StreamingResponse example

Fixes #14680
pull/14681/head
Casper da Costa-Luis 6 months ago
parent
commit
7f49f35620
No known key found for this signature in database GPG Key ID: D88C553DBD362CDE
  1. 10
      docs/en/docs/advanced/custom-response.md
  2. 3
      docs_src/custom_response/tutorial007_py310.py

10
docs/en/docs/advanced/custom-response.md

@ -217,7 +217,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[2,14] *}
{* ../../docs_src/custom_response/tutorial007_py310.py hl[4,17] *}
/// note
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 asyncio.sleep(0)` to give the event loop a chance to handle cancellation.
///
#### Using `StreamingResponse` with file-like objects { #using-streamingresponse-with-file-like-objects }

3
docs_src/custom_response/tutorial007_py310.py

@ -1,3 +1,5 @@
import asyncio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
@ -7,6 +9,7 @@ app = FastAPI()
async def fake_video_streamer():
for i in range(10):
yield b"some fake video bytes"
await asyncio.sleep(0)
@app.get("/")

Loading…
Cancel
Save