Browse Source

Fix issue: Title: StreamingResponse doc example needs correction

Body:
[`StreamingResponse` docs](https://fastapi.tiangolo.com/advanced/custom-response/?h=responses#streamingresponse) state:

> Takes an async generator or a normal generator/iterator

However based on https://github.com/Kludex/starlette/discussions/1776#discussioncomment-3207518 `async` generetors need something `await`ed to work:

```py
import asyncio
from time import sleep
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

async def fake_video_streamer():
    for i in range(10):
        sleep(0.1)
        yield b"some fake video bytes"
        # await asyncio.sleep(0)  # <-- uncomment to fix example

@app.get("/")
async def main():
    """
    this is as per
    https://fastapi.tiangolo.com/advanced/custom-response/?h=responses#streamingresponse
    but does not to work (blocks for 1 sec, then returns all chunks at once):
      curl -sNo- localhost:8000
      wget -qO- localhost:8000
    """
    return StreamingResponse(fake_video_streamer())
```

- `uvicorn==0.40.0`
- `fastapi==0.128.0`

--- Comments ---

User: casperdcl
It seems based on https://github.com/Kludex/starlette/discussions/1776#discussioncomment-3207518 that `await asyncio.sleep(0)` needs to be added to the documented example to work.

User: mirza-mohibul-hasan
Hi @casperdcl, thanks for raising this. I understand the issue and the root cause with async generators blocking without an await. If the fix isn’t already finalized, I’d be happy to work on this or help refine the docs/validate the example. Please let me know if that works for you.

User: casperdcl
fixed in #14681
pull/14859/head
Akash Wankhede 5 months ago
parent
commit
543d62a5fa
  1. 39
      docs/en/docs/advanced/custom-response.md

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

@ -1,3 +1,4 @@
markdown
# Custom Response - HTML, Stream, File, others { #custom-response-html-stream-file-others }
By default, **FastAPI** will return the responses using `JSONResponse`.
@ -215,7 +216,7 @@ You can also use the `status_code` parameter combined with the `response_class`
### `StreamingResponse` { #streamingresponse }
Takes an async generator or a normal generator/iterator and streams the response body.
Takes an async generator or a normal generator/iterator and streams the response body. When using an async generator, ensure that it includes an `await` statement to function properly.
{* ../../docs_src/custom_response/tutorial007_py39.py hl[2,14] *}
@ -276,38 +277,4 @@ You could create a `CustomORJSONResponse`. The main thing you have to do is crea
{* ../../docs_src/custom_response/tutorial009c_py39.py hl[9:14,17] *}
Now instead of returning:
```json
{"message": "Hello World"}
```
...this response will return:
```json
{
"message": "Hello World"
}
```
Of course, you will probably find much better ways to take advantage of this than formatting JSON. 😉
## Default response class { #default-response-class }
When creating a **FastAPI** class instance or an `APIRouter` you can specify which response class to use by default.
The parameter that defines this is `default_response_class`.
In the example below, **FastAPI** will use `ORJSONResponse` by default, in all *path operations*, instead of `JSONResponse`.
{* ../../docs_src/custom_response/tutorial010_py39.py hl[2,4] *}
/// tip
You can still override `response_class` in *path operations* as before.
///
## Additional documentation { #additional-documentation }
You can also declare the media type and many other details in OpenAPI using `responses`: [Additional Responses in OpenAPI](additional-responses.md){.internal-link target=_blank}.
Now instead of returning:
Loading…
Cancel
Save