Skip to content

Add support for StreamedContent with specific content length #374

@RobertoPrevato

Description

@RobertoPrevato

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions