Skip to content
Myr

Simplify ASGI dispatch (#560)

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

* Simplify ASGI dispatch * Blackify * Linting

authored by Tom Christie · committed by GitHub · parent 296c9b4 · Browse files · 1 file+19 added−80 removed
This commit

State

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

Diff stats

1 file+19 added−80 removed

  • other:+19 added−80 removed

1 file+19 added−80 removed

modified:httpx/dispatch/asgi.py+19 added-80 removed
80 unmodified lines
81 "client": self.client,82 "root_path": self.root_path,83 }84 app = MessageLoggerASGIMiddleware(self.app, logger=logger)85 app_exc = None85 status_code = None86 headers = None88 response_started_or_failed = self.backend.create_event()89 response_body = BodyIterator(self.backend)87 body_parts = []88 request_stream = request.stream()89 response_started = False90 response_complete = False9192 async def receive() -> dict:93 try:94 body = await request_stream.__anext__()
1 unmodified line
96 return {"type": "http.request", "body": b"", "more_body": False}97 return {"type": "http.request", "body": body, "more_body": True}9899 async def send(message: dict) -> None:100 nonlocal status_code, headers100 nonlocal status_code, headers, body_parts101 nonlocal response_started, response_complete102103 if message["type"] == "http.response.start":104 assert not response_started105106 status_code = message["status"]107 headers = message.get("headers", [])105 response_started_or_failed.set()108 response_started = True109110 elif message["type"] == "http.response.body":111 assert not response_complete112 body = message.get("body", b"")113 more_body = message.get("more_body", False)114115 if body and request.method != "HEAD":112 await response_body.put(body)116 body_parts.append(body)117118 if not more_body:115 await response_body.mark_as_done()119 response_complete = True120117 async def run_app() -> None:118 nonlocal app_exc119 try:120 await app(scope, receive, send)121 except Exception as exc:122 app_exc = exc123 finally:121 try:122 await app(scope, receive, send)123 except Exception:124 if self.raise_app_exceptions or not response_complete:125 raise124 await response_body.mark_as_done()125 response_started_or_failed.set()126127 # Using the background manager here *works*, but it is weak design because128 # the background task isn't strictly context-managed.129 # We could consider refactoring the other uses of this abstraction130 # (mainly sending/receiving request/response data in h11 and h2 dispatchers),131 # and see if that allows us to come back here and refactor things out.132 background = await self.backend.background_manager(run_app).__aenter__()133134 await response_started_or_failed.wait()135136 if app_exc is not None and self.raise_app_exceptions:137 await background.close(app_exc)138 raise app_exc139140 assert status_code is not None, "application did not return a response."127 assert response_complete128 assert status_code is not None129 assert headers is not None130143 async def on_close() -> None:144 await response_body.drain()145 await background.close(app_exc)146 if app_exc is not None and self.raise_app_exceptions:147 raise app_exc148131 return Response(132 status_code=status_code,133 http_version="HTTP/1.1",134 headers=headers,153 content=response_body.iterate(),154 on_close=on_close,135 content=b"".join(body_parts),136 request=request,137 )157158159class BodyIterator:160 """161 Provides a byte-iterator interface that the client can use to162 ingest the response content from.163 """164165 def __init__(self, backend: ConcurrencyBackend) -> None:166 self._queue = backend.create_queue(max_size=1)167 self._done = object()168169 async def iterate(self) -> typing.AsyncIterator[bytes]:170 """171 A byte-iterator, used by the client to consume the response body.172 """173 while True:174 data = await self._queue.get()175 if data is self._done:176 break177 assert isinstance(data, bytes)178 yield data179180 async def drain(self) -> None:181 """182 Drain any remaining body, in order to allow any blocked `put()` calls183 to complete.184 """185 async for chunk in self.iterate():186 pass # pragma: no cover187188 async def put(self, data: bytes) -> None:189 """190 Used by the server to add data to the response body.191 """192 await self._queue.put(data)193194 async def mark_as_done(self) -> None:195 """196 Used by the server to signal the end of the response body.197 """198 await self._queue.put(self._done)