pallets / pallets/quart

Streaming response API is not compatible with async context managers

Open
#229 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
3.7k
Forks
206
PR merge metrics
No merged PRs in 30d

Description

The current streaming response API requires returning an async generator. This is really awkward to use given that so many async classes are not RAII - initialised with __init__ and finalised with __del__ - but are async context managers, initialised with __aenter__ and finalised with __aexit__.

For example, to use httpx's streaming responses in a quart streaming response, I came up with this abomination:

client = httpx.AsyncClient()

@app.route(...)
async def proxy_response():
    resp = await client.stream('GET', some_url).__aenter__()
    if resp.status_code == 404:
        return "not found", 404
    async def iter_response():
        try:
            async for chunk in resp.aiter_bytes():
                yield chunk
        finally:
            await resp.__aexit__(None, None, None)
    return iter_response(), 200

I don't think this is necessarily right because if the iter_response generator is discarded because the remote client hangs up, then maybe? GeneratorExit is raised but I doubt that there is a task that would actually run the await in the finally block.

Plain ASGI doesn't have this problem: you can just wrap async context managers around a bunch of

await send({'type': 'http.response.body', 'body': data})

so

async def app(scope, send, receive):
    async with client.stream('GET', some_url) as resp:
        if resp.status_code == 404:
            await send({'type': 'http.response.start', 'status': 404})
            await send({'type': 'http.response.body', 'body': "Not found"})
            return

        await send({'type': 'http.response.start', 'status': 200})
        async for chunk in resp.aiter_bytes():
            await send({'type': 'http.response.body', 'body': chunk})

I would propose an API in Quart that allows this, e.g.

@app.route(...)
async def proxy_response():
     async with client.stream('GET', some_url) as resp:
         if resp.status_code == 404:
             return "not found", 404
         async with quart.streaming_response(200, headers={'Content-Length': resp.headers['Content-Length']) as send:
             async for chunk in resp.aiter_bytes():
                 await send(chunk)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start from Quart's current streaming response API and the route handler pattern shown in the issue, then compare it with the ASGI send flow and async context-manager lifecycle. Define and implement the proposed interface only after resolving how status, headers, streaming chunks, early returns, and cleanup should behave; done means async context managers can safely drive a Quart streaming response.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
api, backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.