Skip to content
Myr

Header refinements (#1248)

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

authored by Tom Christie · committed by GitHub · parent def9f1c · Browse files · 4 files+59 added−35 removed
This commit

State

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

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

4 files+59 added−35 removed

  • tests:+34 added−0 removed
  • other:+25 added−35 removed

4 files+59 added−35 removed

modified:httpx/_client.py+20 added-7 removed
3 unmodified lines
4from types import TracebackType56import httpcore78from .__version__ import __version__9from ._auth import Auth, BasicAuth, FunctionAuth10from ._config import (11 DEFAULT_LIMITS,12 DEFAULT_MAX_REDIRECTS,
5 unmodified lines
18 UnsetType,19 create_ssl_context,20)21from ._content_streams import ContentStream22from ._decoders import SUPPORTED_DECODERS23from ._exceptions import (24 HTTPCORE_EXC_MAP,25 InvalidURL,26 RemoteProtocolError,
29 unmodified lines
5657logger = get_logger(__name__)5859KEEPALIVE_EXPIRY = 5.060USER_AGENT = f"python-httpx/{__version__}"61ACCEPT_ENCODING = ", ".join(62 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]63)646566class BaseClient:67 def __init__(
11 unmodified lines
79 self._base_url = self._enforce_trailing_slash(URL(base_url))8081 self._auth = self._build_auth(auth)82 self._params = QueryParams(params)77 self._headers = Headers(headers)83 self.headers = Headers(headers)84 self._cookies = Cookies(cookies)85 self._timeout = Timeout(timeout)86 self.max_redirects = max_redirects87 self._trust_env = trust_env
78 unmodified lines
166 return self._headers167168 @headers.setter169 def headers(self, headers: HeaderTypes) -> None:164 self._headers = Headers(headers)170 client_headers = Headers(171 {172 b"Accept": b"*/*",173 b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"),174 b"Connection": b"keep-alive",175 b"User-Agent": USER_AGENT.encode("ascii"),176 }177 )178 client_headers.update(headers)179 self._headers = client_headers180181 @property182 def cookies(self) -> Cookies:183 """
129 unmodified lines
313 """314 Merge a headers argument together with any headers on the client,315 to create the headers used for the outgoing request.316 """302 if headers or self.headers:303 merged_headers = Headers(self.headers)304 merged_headers.update(headers)305 return merged_headers317 merged_headers = Headers(self.headers)318 merged_headers.update(headers)319 return merged_headers306 return headers320321 def _merge_queryparams(322 self, params: QueryParamTypes = None323 ) -> typing.Optional[QueryParamTypes]:
1452 unmodified lines
modified:httpx/_models.py+5 added-28 removed
12 unmodified lines
13import chardet14import rfc398615import rfc3986.exceptions1617from .__version__ import __version__17from ._content_streams import ByteStream, ContentStream, encode18from ._decoders import (19 SUPPORTED_DECODERS,20 Decoder,
80 unmodified lines
101 return self._uri_reference.userinfo or ""102103 @property104 def username(self) -> str:106 userinfo = self._uri_reference.userinfo or ""107 return unquote(userinfo.partition(":")[0])105 return unquote(self.userinfo.partition(":")[0])106107 @property108 def password(self) -> str:111 userinfo = self._uri_reference.userinfo or ""112 return unquote(userinfo.partition(":")[2])109 return unquote(self.userinfo.partition(":")[2])110111 @property112 def host(self) -> str:113 return self._uri_reference.host or ""
462 unmodified lines
576 warnings.warn(message, DeprecationWarning)577 return self.get_list(key, split_commas=split_commas)578579583USER_AGENT = f"python-httpx/{__version__}"584ACCEPT_ENCODING = ", ".join(585 [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]586)587588580class Request:581 def __init__(582 self,583 method: str,
33 unmodified lines
617 has_host = "host" in self.headers618 has_content_length = (619 "content-length" in self.headers or "transfer-encoding" in self.headers620 )630 has_user_agent = "user-agent" in self.headers631 has_accept = "accept" in self.headers632 has_accept_encoding = "accept-encoding" in self.headers633 has_connection = "connection" in self.headers621635 if not has_host:636 url = self.url637 if url.userinfo:638 url = url.copy_with(username=None, password=None)639 auto_headers.append((b"host", url.authority.encode("ascii")))622 if not has_host and self.url.authority:623 host = self.url.copy_with(username=None, password=None).authority624 auto_headers.append((b"host", host.encode("ascii")))625 if not has_content_length and self.method in ("POST", "PUT", "PATCH"):626 auto_headers.append((b"content-length", b"0"))642 if not has_user_agent:643 auto_headers.append((b"user-agent", USER_AGENT.encode("ascii")))644 if not has_accept:645 auto_headers.append((b"accept", b"*/*"))646 if not has_accept_encoding:647 auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))648 if not has_connection:649 auto_headers.append((b"connection", b"keep-alive"))627628 self.headers = Headers(auto_headers + self.headers.raw)629630 @property
608 unmodified lines
modified:tests/client/test_headers.py+22 added
122 unmodified lines
123 }124 }125126127def test_remove_default_header():128 """129 Remove a default header from the Client.130 """131 url = "http://example.org/echo_headers"132133 client = httpx.Client(transport=MockTransport())134 del client.headers["User-Agent"]135136 response = client.get(url)137138 assert response.status_code == 200139 assert response.json() == {140 "headers": {141 "accept": "*/*",142 "accept-encoding": "gzip, deflate, br",143 "connection": "keep-alive",144 "host": "example.org",145 }146 }147148149def test_header_does_not_exist():150 headers = httpx.Headers({"foo": "bar"})151 with pytest.raises(KeyError):152 del headers["baz"]
52 unmodified lines
modified:tests/models/test_requests.py+12 added
32 unmodified lines
33 assert request.headers["Content-Type"] == "application/json"34 assert request.content == b'{"test": 123}'353637def test_headers():38 request = httpx.Request("POST", "http://example.org", json={"test": 123})3940 assert request.headers == httpx.Headers(41 {42 "Host": "example.org",43 "Content-Type": "application/json",44 "Content-Length": "13",45 }46 )474849def test_read_and_stream_data():50 # Ensure a request may still be streamed if it has been read.51 # Needed for cases such as authentication classes that read the request body.52 request = httpx.Request("POST", "http://example.org", json={"test": 123})
89 unmodified lines