Skip to content
Myr

ASGI: Wait for response to complete before sending disconnect message (#919)

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

* asgi: Wait for response to complete before sending disconnect message * Dial back type checking + remove concurrency module * Remove somewhat redundant comment

authored by Jamie Hewland · committed by GitHub · parent 560b119 · Browse files · 4 files+31 added−8 removed
This commit

State

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

Diff stats

4 files+31 added−8 removed

  • tests:+1 added−2 removed
  • other:+30 added−6 removed

4 files+31 added−8 removed

modified:httpx/_dispatch/asgi.py+28 added-6 removed
1import typing2from typing import Callable, Dict, List, Optional, Tuple34import httpcore5import sniffio67from .._content_streams import ByteStream89if typing.TYPE_CHECKING: # pragma: no cover10 import asyncio11 import trio1213 Event = typing.Union[asyncio.Event, trio.Event]141516def create_event() -> "Event":17 if sniffio.current_async_library() == "trio":18 import trio1920 return trio.Event()21 else:22 import asyncio2324 return asyncio.Event()252627class ASGIDispatch(httpcore.AsyncHTTPTransport):28 """29 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.30 The simplest way to use this functionality is to use the `app` argument.
63 unmodified lines
94 }95 status_code = None96 response_headers = None97 body_parts = []98 request_complete = False99 response_started = False80 response_complete = False100 response_complete = create_event()101102 headers = [] if headers is None else headers103 stream = ByteStream(b"") if stream is None else stream104105 request_body_chunks = stream.__aiter__()106107 async def receive() -> dict:88 nonlocal response_complete108 nonlocal request_complete, response_complete10990 if response_complete:110 if request_complete:111 await response_complete.wait()112 return {"type": "http.disconnect"}113114 try:115 body = await request_body_chunks.__anext__()116 except StopAsyncIteration:117 request_complete = True118 return {"type": "http.request", "body": b"", "more_body": False}119 return {"type": "http.request", "body": body, "more_body": True}120121 async def send(message: dict) -> None:
7 unmodified lines
129 response_headers = message.get("headers", [])130 response_started = True131132 elif message["type"] == "http.response.body":111 assert not response_complete133 assert not response_complete.is_set()134 body = message.get("body", b"")135 more_body = message.get("more_body", False)136137 if body and method != b"HEAD":138 body_parts.append(body)139140 if not more_body:119 response_complete = True141 response_complete.set()142143 try:144 await self.app(scope, receive, send)145 except Exception:146 if self.raise_app_exceptions or not response_complete:147 raise148127 assert response_complete149 assert response_complete.is_set()150 assert status_code is not None151 assert response_headers is not None152153 stream = ByteStream(b"".join(body_parts))
2 unmodified lines
modified:tests/test_asgi.py+1 added-2 removed
67 unmodified lines
68 with pytest.raises(ValueError):69 await client.get("http://www.example.org/")707172@pytest.mark.asyncio73async def test_asgi_disconnect_after_response_complete():72async def test_asgi_disconnect_after_response_complete(async_environment):73 disconnect = False7475 async def read_body(scope, receive, send):76 nonlocal disconnect
25 unmodified lines
modified:requirements.txt+1 added
24 unmodified lines
25pytest-asyncio26pytest-trio27pytest-cov28trio29trio-typing30trustme31uvicorn32seed-isort-config33
1 unmodified line
modified:setup.py+1 added
59 unmodified lines
60 "chardet==3.*",61 "idna==2.*",62 "rfc3986>=1.3,<2",63 "httpcore>=0.8.3",64 "sniffio",65 ],66 classifiers=[67 "Development Status :: 4 - Beta",68 "Environment :: Web Environment",
13 unmodified lines