Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion docs/en/docs/advanced/custom-response.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,17 @@ 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[3,16] *}

/// 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.

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.

This would be even more important with large or infinite streams.

///

#### Using `StreamingResponse` with file-like objects { #using-streamingresponse-with-file-like-objects }

Expand Down
2 changes: 2 additions & 0 deletions docs_src/custom_response/tutorial007_py310.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import anyio
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

Expand All @@ -7,6 +8,7 @@
async def fake_video_streamer():
for i in range(10):
yield b"some fake video bytes"
await anyio.sleep(0)


@app.get("/")
Expand Down