Skip to content
Myr

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

5 files+141 added−14 removed

modified:httpcore/compat.py+1 added-1 removed
1try:2 import brotli3except ImportError:4 brotli = None4 brotli = None # pragma: nocover
modified:httpcore/connections.py+1 added-7 removed
41 unmodified lines
4243 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.headers4752 headers = [host_header, content_length] + request.headers5348 #  Start sending the request.49 event = h11.Request(method=method, target=target, headers=headers)50 await self._send_event(event)51
72 unmodified lines
modified:httpcore/datastructures.py+40 added-4 removed
1import typing2from urllib.parse import urlsplit34from .decoders import SUPPORTED_DECODERS, Decoder, IdentityDecoder, MultiDecoder4from .decoders import (5 ACCEPT_ENCODING,6 SUPPORTED_DECODERS,7 Decoder,8 IdentityDecoder,9 MultiDecoder,10)11from .exceptions import ResponseClosed, StreamConsumed121314class URL:
49 unmodified lines
64class 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.headers8384 def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:85 has_host = False86 has_content_length = False87 has_accept_encoding = False8889 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 = True9798 headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]99100 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))110111 return headers112113 async def stream(self) -> typing.AsyncIterator[bytes]:114 assert self.is_streaming115116 async for part in self.body_aiter:
49 unmodified lines
166167 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 lines
modified:httpcore/decoders.py+7 added-2 removed
105 unmodified lines
106 return data107108109SUPPORTED_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}115116117if brotli is None:118 SUPPORTED_DECODERS.pop(b"br") # pragma: nocover119120121ACCEPT_ENCODING = b", ".join(122 [key for key in SUPPORTED_DECODERS.keys() if key != b"identity"]123)
added:tests/test_requests.py+92 added
1import pytest23import httpcore456def 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 ]121314def 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 ]212223def test_transfer_encoding_header():24 async def streaming_body(data):25 yield data # pragma: nocover2627 body = streaming_body(b"test 123")2829 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 ]353637def test_override_host_header():38 headers = [(b"host", b"1.2.3.4:80")]3940 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 ]454647def test_override_accept_encoding_header():48 headers = [(b"accept-encoding", b"identity")]4950 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 ]555657def test_override_content_length_header():58 async def streaming_body(data):59 yield data # pragma: nocover6061 body = streaming_body(b"test 123")62 headers = [(b"content-length", b"8")]6364 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 ]707172def 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 == "/"7778 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"828384def test_invalid_urls():85 with pytest.raises(ValueError):86 httpcore.Request("GET", "example.org")8788 with pytest.raises(ValueError):89 httpcore.Request("GET", "invalid://example.org")9091 with pytest.raises(ValueError):92 httpcore.Request("GET", "http:///foo")