Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow streamable response as response_class to work #11440

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

92dev
Copy link

@92dev 92dev commented Apr 15, 2024

Basically classes such as StreamingResponse in starlette cannot work unless specified directly in the response-type due to this serialization concept (which they always fallback to use JSON)

There is the alternative which I opted out of for now, which is pass a response_serialize: bool parameter throughout the entire flow, it might be better but I wanted to avoid API changes (even through defaults) until any maintainer gives his opinion on the change

example usage:

from fastapi.responses import StreamingResponse

# Here `response_class` is only used for documentation
@app.get('/test_before', response_class=StreamingResponse)
async def before_fix(msg: str):
    async def txt_generator():
        for i in range(10):
            yield f'event: something\ndata: {i}\n\n'
    return StreamingResponse(txt_generator())

# Here `response_class` is actually working
@app.get('/test_after', response_class=StreamingResponse)
async def after_fix(msg: str):
    async def txt_generator():
        for i in range(10):
            yield f'event: something\ndata: {i}\n\n'
    return txt_generator()

Basically classes such as `StreamingResponse` in `starlette` cannot work unless specified directly in the response-type due to this serialization concept (which they always fallback to use JSON)

There is the alternative which I opted out of for now, which is pass a `response_serialize: bool` parameter throughout the entire flow, it might be better but I wanted to avoid API changes (even through defaults) until any maintainer gives his opinion on the change

example usage:
```
# Here `response_class` is only used for documentation
@app.get('/test_before', response_class=StreamingResponse)
async def before_fix(msg: str):
    async def txt_generator():
        for i in range(10):
            yield f'event: something\ndata: {i}\n\n'
    return StreamingResponse(txt_generator())

# Here `response_class` is actually working
@app.get('/test_after', response_class=StreamingResponse)
async def after_fix(msg: str):
    async def txt_generator():
        for i in range(10):
            yield f'event: something\ndata: {i}\n\n'
    returntxt_generator()
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants