Skip to content
Myr

asgi: Send http.disconnect message on receive() after response complete (#909)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Jamie Hewland · committed by GitHub · parent bed3d8b · Browse files · 2 files+38 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

2 files+38 added−0 removed

  • tests:+33 added−0 removed
  • other:+5 added−0 removed

2 files+38 added−0 removed

modified:httpx/_dispatch/asgi.py+5 added
83 unmodified lines
8485 request_body_chunks = stream.__aiter__()8687 async def receive() -> dict:88 nonlocal response_complete8990 if response_complete:91 return {"type": "http.disconnect"}9293 try:94 body = await request_body_chunks.__anext__()95 except StopAsyncIteration:96 return {"type": "http.request", "body": b"", "more_body": False}
37 unmodified lines
modified:tests/test_asgi.py+33 added
65 unmodified lines
66async def test_asgi_exc_after_response():67 client = httpx.AsyncClient(app=raise_exc_after_response)68 with pytest.raises(ValueError):69 await client.get("http://www.example.org/")707172@pytest.mark.asyncio73async def test_asgi_disconnect_after_response_complete():74 disconnect = False7576 async def read_body(scope, receive, send):77 nonlocal disconnect7879 status = 20080 headers = [(b"content-type", "text/plain")]8182 await send(83 {"type": "http.response.start", "status": status, "headers": headers}84 )85 more_body = True86 while more_body:87 message = await receive()88 more_body = message.get("more_body", False)8990 await send({"type": "http.response.body", "body": b"", "more_body": False})9192 # The ASGI spec says of the Disconnect message:93 # "Sent to the application when a HTTP connection is closed or if receive is94 # called after a response has been sent."95 # So if receive() is called again, the disconnect message should be received96 message = await receive()97 disconnect = message.get("type") == "http.disconnect"9899 client = httpx.AsyncClient(app=read_body)100 response = await client.post("http://www.example.org/", data=b"example")101 assert response.status_code == 200102 assert disconnect