Merge pull request #3 from encode/request-auto-headers
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Request auto headers
authored by Tom Christie · committed by GitHub · parents 60befed, ee6f42a · Browse files · 5 files·+141 added−14 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+141 added−14 removed
- tests:+92 added−0 removed
- other:+49 added−14 removed
Provenance
- Commit
fae53e2- Tree
618140b- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
60befed- Parent 2
ee6f42a
5 files changed+141 added−14 removed
modified:httpcore/compat.py+1 added-1 removed
1 try:2 import brotli3 except ImportError:4- brotli = None4+ brotli = None # pragma: nocovermodified:httpcore/connections.py+1 added-7 removed
41 unmodified lines42 43 async def send(self, request: Request, stream: bool = False) -> Response:44 method = request.method.encode()45 target = request.url.target46- host_header = (b"host", request.url.netloc.encode("ascii"))47- if request.is_streaming:48- content_length = (b"transfer-encoding", b"chunked")49- else:50- content_length = (b"content-length", str(len(request.body)).encode())46+ headers = request.headers47 52- headers = [host_header, content_length] + request.headers53-48 # Start sending the request.49 event = h11.Request(method=method, target=target, headers=headers)50 await self._send_event(event)51 72 unmodified linesmodified:httpcore/datastructures.py+40 added-4 removed
1 import typing2 from urllib.parse import urlsplit3 4-from .decoders import SUPPORTED_DECODERS, Decoder, IdentityDecoder, MultiDecoder4+from .decoders import (5+ ACCEPT_ENCODING,6+ SUPPORTED_DECODERS,7+ Decoder,8+ IdentityDecoder,9+ MultiDecoder,10+)11 from .exceptions import ResponseClosed, StreamConsumed12 13 14 class URL:49 unmodified lines64 class Request:65 def __init__(66 self,67 method: str,62- url: URL,68+ url: typing.Union[str, URL],69 *,70 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),71 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",72 ):73 self.method = method68- self.url = url74+ self.url = URL(url) if isinstance(url, str) else url75 self.headers = list(headers)76 if isinstance(body, bytes):77 self.is_streaming = False78 self.body = body79 else:80 self.is_streaming = True81 self.body_aiter = body82+ self.headers = self._auto_headers() + self.headers83 84+ def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:85+ has_host = False86+ has_content_length = False87+ has_accept_encoding = False88+89+ for header, value in self.headers:90+ header = header.strip().lower()91+ if header == b"host":92+ has_host = True93+ elif header in (b"content-length", b"transfer-encoding"):94+ has_content_length = True95+ elif header == b"accept-encoding":96+ has_accept_encoding = True97+98+ headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]99+100+ if not has_host:101+ headers.append((b"host", self.url.netloc.encode("ascii")))102+ if not has_content_length:103+ if self.is_streaming:104+ headers.append((b"transfer-encoding", b"chunked"))105+ elif self.body:106+ content_length = str(len(self.body)).encode()107+ headers.append((b"content-length", content_length))108+ if not has_accept_encoding:109+ headers.append((b"accept-encoding", ACCEPT_ENCODING))110+111+ return headers112+113 async def stream(self) -> typing.AsyncIterator[bytes]:114 assert self.is_streaming115 116 async for part in self.body_aiter:49 unmodified lines166 167 async def stream(self) -> typing.AsyncIterator[bytes]:168 """169 A byte-iterator over the decoded response content.134- This will allow us to handle gzip, deflate, and brotli encoded responses.170+ This allows us to handle gzip, deflate, and brotli encoded responses.171 """172 if hasattr(self, "body"):173 yield self.body174 else:22 unmodified linesmodified:httpcore/decoders.py+7 added-2 removed
105 unmodified lines106 return data107 108 109 SUPPORTED_DECODERS = {110- b"gzip": GZipDecoder,111- b"deflate": DeflateDecoder,110 b"identity": IdentityDecoder,111+ b"deflate": DeflateDecoder,112+ b"gzip": GZipDecoder,113 b"br": BrotliDecoder,114 }115 116 117 if brotli is None:118 SUPPORTED_DECODERS.pop(b"br") # pragma: nocover119+120+121+ACCEPT_ENCODING = b", ".join(122+ [key for key in SUPPORTED_DECODERS.keys() if key != b"identity"]123+)added:tests/test_requests.py+92 added
1+import pytest2+3+import httpcore4+5+6+def test_host_header():7+ request = httpcore.Request("GET", "http://example.org")8+ assert request.headers == [9+ (b"host", b"example.org"),10+ (b"accept-encoding", b"deflate, gzip, br"),11+ ]12+13+14+def test_content_length_header():15+ request = httpcore.Request("POST", "http://example.org", body=b"test 123")16+ assert request.headers == [17+ (b"host", b"example.org"),18+ (b"content-length", b"8"),19+ (b"accept-encoding", b"deflate, gzip, br"),20+ ]21+22+23+def test_transfer_encoding_header():24+ async def streaming_body(data):25+ yield data # pragma: nocover26+27+ body = streaming_body(b"test 123")28+29+ request = httpcore.Request("POST", "http://example.org", body=body)30+ assert request.headers == [31+ (b"host", b"example.org"),32+ (b"transfer-encoding", b"chunked"),33+ (b"accept-encoding", b"deflate, gzip, br"),34+ ]35+36+37+def test_override_host_header():38+ headers = [(b"host", b"1.2.3.4:80")]39+40+ request = httpcore.Request("GET", "http://example.org", headers=headers)41+ assert request.headers == [42+ (b"accept-encoding", b"deflate, gzip, br"),43+ (b"host", b"1.2.3.4:80"),44+ ]45+46+47+def test_override_accept_encoding_header():48+ headers = [(b"accept-encoding", b"identity")]49+50+ request = httpcore.Request("GET", "http://example.org", headers=headers)51+ assert request.headers == [52+ (b"host", b"example.org"),53+ (b"accept-encoding", b"identity"),54+ ]55+56+57+def test_override_content_length_header():58+ async def streaming_body(data):59+ yield data # pragma: nocover60+61+ body = streaming_body(b"test 123")62+ headers = [(b"content-length", b"8")]63+64+ request = httpcore.Request("POST", "http://example.org", body=body, headers=headers)65+ assert request.headers == [66+ (b"host", b"example.org"),67+ (b"accept-encoding", b"deflate, gzip, br"),68+ (b"content-length", b"8"),69+ ]70+71+72+def test_url():73+ request = httpcore.Request("GET", "http://example.org")74+ assert request.url.scheme == "http"75+ assert request.url.port == 8076+ assert request.url.target == "/"77+78+ request = httpcore.Request("GET", "https://example.org/abc?foo=bar")79+ assert request.url.scheme == "https"80+ assert request.url.port == 44381+ assert request.url.target == "/abc?foo=bar"82+83+84+def test_invalid_urls():85+ with pytest.raises(ValueError):86+ httpcore.Request("GET", "example.org")87+88+ with pytest.raises(ValueError):89+ httpcore.Request("GET", "invalid://example.org")90+91+ with pytest.raises(ValueError):92+ httpcore.Request("GET", "http:///foo")