Neoteroi / BlackSheep

Fast ASGI web framework for Python
https://www.neoteroi.dev/blacksheep/
MIT License
1.8k stars 75 forks source link

Add support for StreamedContent with specific content length #374

Closed RobertoPrevato closed 1 year ago

RobertoPrevato commented 1 year ago

Currently BlackSheep supports streaming response content using asynchronous generators, and for those always uses transfer-encoding: chunked, meaning that content length is not set as response header, and the length is just determined by the final transmitted chunk.

When implementing a proxy, though, it is best to support proxying responses having a specified content-length even when the response is streamed.

This is to support specifying a content-length when using an async generator. Like in this example:

from blacksheep import Application, Response, StreamedContent

app = Application()

@app.router.get("/")
def home():
    async def data_generator():
        yield b'{"hello":"world",'
        yield b'"lorem":'
        yield b'"ipsum","dolor":"sit"'
        yield b',"amet":"consectetur"}'

    return Response(200, [], StreamedContent(b"application/json", data_generator, 68))  # <<< NOTE!

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, port=44555, lifespan="on")

⚠️ in such cases, of course, it is the responsibility of the user to configure the right content length.