Include host header directly (#109)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Improve HTTP protocol detection * Include host header when request is instantiated * Add raise_app_exceptions * Tweaks to ASGI dispatching * Linting * Don't quote multipart values * Tweak decoder ordering in header * Allow str data in request bodys
authored by Tom Christie · committed by GitHub · parent 04cb3a6 · Browse files · 8 files·+46 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+46 added−26 removed
- other:+46 added−26 removed
Provenance
- Commit
5539b69- Tree
f71a385- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
04cb3a6
8 files changed+46 added−26 removed
modified:http3/dispatch/asgi.py+19 added-8 removed
33 unmodified lines34 35 def __init__(36 self,37 app: typing.Callable,38+ raise_app_exceptions: bool = True,39 root_path: str = "",40 client: typing.Tuple[str, int] = ("127.0.0.1", 123),41 ) -> None:42 self.app = app43+ self.raise_app_exceptions = raise_app_exceptions44 self.root_path = root_path45 self.client = client46 47 async def send(6 unmodified lines54 55 scope = {56 "type": "http",57 "asgi": {"version": "3.0"},58+ "http_version": "1.1",59 "method": request.method,60 "headers": request.headers.raw,61 "scheme": request.url.scheme,62 "path": request.url.path,60- "query": request.url.query.encode("ascii"),63+ "query_string": request.url.query.encode("ascii"),64 "server": request.url.host,65 "client": self.client,66 "root_path": self.root_path,67 }14 unmodified lines82 return {"type": "http.request", "body": b"", "more_body": False}83 return {"type": "http.request", "body": body, "more_body": True}84 85 async def send(message: dict) -> None:83- nonlocal status_code, headers, response_started, response_body86+ nonlocal status_code, headers, response_started, response_body, request87 88 if message["type"] == "http.response.start":89 status_code = message["status"]90 headers = message.get("headers", [])91 response_started.set()92 elif message["type"] == "http.response.body":93 body = message.get("body", b"")94 more_body = message.get("more_body", False)92- if body:95+ if body and request.method != "HEAD":96 await response_body.put(body)97 if not more_body:98 await response_body.done()99 100 async def run_app() -> None:101 nonlocal app, scope, receive, send, app_exc, response_body99-102 try:103 await app(scope, receive, send)104 except Exception as exc:105 app_exc = exc12 unmodified lines118 tasks = {app_task, response_task} # type: typing.Set[asyncio.Task]119 120 await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)121 120- if app_exc is not None:122+ if app_exc is not None and self.raise_app_exceptions:123 raise app_exc124 123- assert response_started.is_set, "application did not return a response."125+ assert response_started.is_set(), "application did not return a response."126 assert status_code is not None127 assert headers is not None128 129 async def on_close() -> None:128- nonlocal app_task130+ nonlocal app_task, response_body131+ await response_body.drain()132 await app_task130- if app_exc is not None:133+ if app_exc is not None and self.raise_app_exceptions:134 raise app_exc135 136 return AsyncResponse(137 status_code=status_code,27 unmodified lines165 break166 assert isinstance(data, bytes)167 yield data168 169+ async def drain(self) -> None:170+ """171+ Drain any remaining body, in order to allow any blocked `put()` calls172+ to complete.173+ """174+ async for chunk in self.iterate():175+ pass # pragma: no cover176+177 async def put(self, data: bytes) -> None:178 """179 Used by the server to add data to the response body.180 """7 unmodified linesmodified:http3/dispatch/http11.py-3 removed
77 unmodified lines78 """79 method = request.method.encode("ascii")80 target = request.url.full_path.encode("ascii")81 headers = request.headers.raw82- if "Host" not in request.headers:83- host = request.url.authority.encode("ascii")84- headers = [(b"host", host)] + headers82 event = h11.Request(method=method, target=target, headers=headers)83 await self._send_event(event, timeout)84 85 async def _send_request_data(99 unmodified linesmodified:http3/dispatch/http2.py+1 added-1 removed
74 unmodified lines75 (b":method", request.method.encode("ascii")),76 (b":authority", request.url.authority.encode("ascii")),77 (b":scheme", request.url.scheme.encode("ascii")),78 (b":path", request.url.full_path.encode("ascii")),79- ] + request.headers.raw79+ ] + [(k, v) for k, v in request.headers.raw if k != b"host"]80 self.h2_state.send_headers(stream_id, headers)81 data_to_send = self.h2_state.data_to_send()82 await self.writer.write(data_to_send, timeout)83 return stream_id91 unmodified linesmodified:http3/dispatch/wsgi.py+3 added-1 removed
33 unmodified lines34 35 def __init__(36 self,37 app: typing.Callable,38+ raise_app_exceptions: bool = True,39 script_name: str = "",40 remote_addr: str = "127.0.0.1",41 ) -> None:42 self.app = app43+ self.raise_app_exceptions = raise_app_exceptions44 self.script_name = script_name45 self.remote_addr = remote_addr46 47 def send(40 unmodified lines88 result = self.app(environ, start_response)89 90 assert seen_status is not None91 assert seen_response_headers is not None90- if seen_exc_info:92+ if seen_exc_info and self.raise_app_exceptions:93 raise seen_exc_info[1]94 95 return Response(96 status_code=int(seen_status.split()[0]),58 unmodified linesmodified:http3/client.py+8 added-3 removed
52 unmodified lines53 max_redirects: int = DEFAULT_MAX_REDIRECTS,54 base_url: URLTypes = None,55 dispatch: typing.Union[AsyncDispatcher, Dispatcher] = None,56 app: typing.Callable = None,57+ raise_app_exceptions: bool = True,58 backend: ConcurrencyBackend = None,59 ):60 if backend is None:61 backend = AsyncioBackend()1 unmodified line63 if app is not None:64 param_count = len(inspect.signature(app).parameters)65 assert param_count in (2, 3)66 if param_count == 2:66- dispatch = WSGIDispatch(app=app)67+ dispatch = WSGIDispatch(68+ app=app, raise_app_exceptions=raise_app_exceptions69+ )70 else:68- dispatch = ASGIDispatch(app=app)71+ dispatch = ASGIDispatch(72+ app=app, raise_app_exceptions=raise_app_exceptions73+ )74 75 if dispatch is None:76 async_dispatch = ConnectionPool(77 verify=verify,484 unmodified lines562 """563 If the request data is an bytes iterator then return an async bytes564 iterator onto the request data.565 """561- if data is None or isinstance(data, (bytes, dict)):566+ if data is None or isinstance(data, (str, bytes, dict)):567 return data568 569 # Coerce an iterator into an async iterator, with each item in the570 # iteration running as a thread-pooled operation.316 unmodified linesmodified:http3/decoders.py+1 added-1 removed
132 unmodified lines133 134 135 SUPPORTED_DECODERS = {136 "identity": IdentityDecoder,137- "deflate": DeflateDecoder,137 "gzip": GZipDecoder,138+ "deflate": DeflateDecoder,139 "br": BrotliDecoder,140 }141 142 7 unmodified linesmodified:http3/models.py+9 added-4 removed
49 unmodified lines50 typing.Tuple[typing.Union[str, bytes], typing.Union[str, bytes]],51 typing.Callable[["AsyncRequest"], "AsyncRequest"],52 ]53 54-AsyncRequestData = typing.Union[dict, bytes, typing.AsyncIterator[bytes]]54+AsyncRequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]55 56-RequestData = typing.Union[dict, bytes, typing.Iterator[bytes]]56+RequestData = typing.Union[dict, str, bytes, typing.Iterator[bytes]]57 58 RequestFiles = typing.Dict[59 str,60 typing.Union[465 unmodified lines526 is_streaming = getattr(self, "is_streaming", False)527 528 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]529 530+ has_host = "host" in self.headers531 has_user_agent = "user-agent" in self.headers532 has_accept = "accept" in self.headers533 has_content_length = (534 "content-length" in self.headers or "transfer-encoding" in self.headers535 )536 has_accept_encoding = "accept-encoding" in self.headers537 538+ if not has_host:539+ auto_headers.append((b"host", self.url.authority.encode("ascii")))540 if not has_user_agent:541 auto_headers.append((b"user-agent", b"http3"))542 if not has_accept:543 auto_headers.append((b"accept", b"*/*"))43 unmodified lines587 self.is_streaming = False588 self.content = content589 if content_type:590 self.headers["Content-Type"] = content_type588- elif isinstance(data, bytes):591+ elif isinstance(data, (str, bytes)):592+ data = data.encode("utf-8") if isinstance(data, str) else data593 self.is_streaming = False594 self.content = data595 else:596 assert hasattr(data, "__aiter__")40 unmodified lines637 self.is_streaming = False638 self.content = content639 if content_type:640 self.headers["Content-Type"] = content_type637- elif isinstance(data, bytes):641+ elif isinstance(data, (str, bytes)):642+ data = data.encode("utf-8") if isinstance(data, str) else data643 self.is_streaming = False644 self.content = data645 else:646 assert hasattr(data, "__iter__")508 unmodified linesmodified:http3/multipart.py+5 added-5 removed
1 unmodified line2 import mimetypes3 import os4 import typing5 from io import BytesIO6-from urllib.parse import quote_plus6+from urllib.parse import quote7 8 9 class Field:10 def render_headers(self) -> bytes:8 unmodified lines19 self.name = name20 self.value = value21 22 def render_headers(self) -> bytes:23- name = quote_plus(self.name, encoding="utf-8").encode("ascii")23+ name = quote(self.name, encoding="utf-8").encode("ascii")24 return b"".join(25 [b'Content-Disposition: form-data; name="', name, b'"\r\n' b"\r\n"]26 )27 28 def render_data(self) -> bytes:29- return quote_plus(self.value, encoding="utf-8").encode("ascii")29+ return self.value.encode("utf-8")30 31 32 class FileField(Field):33 def __init__(14 unmodified lines48 def guess_content_type(self) -> str:49 return mimetypes.guess_type(self.filename)[0] or "application/octet-stream"50 51 def render_headers(self) -> bytes:52- name = quote_plus(self.name, encoding="utf-8").encode("ascii")53- filename = quote_plus(self.filename, encoding="utf-8").encode("ascii")52+ name = quote(self.name, encoding="utf-8").encode("ascii")53+ filename = quote(self.filename, encoding="utf-8").encode("ascii")54 content_type = self.content_type.encode("ascii")55 return b"".join(56 [57 b'Content-Disposition: form-data; name="',43 unmodified lines