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
Provenance
- Commit
19b863a- Tree
e63a778- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
def9f1c
4 files changed+59 added−35 removed
modified:httpx/_client.py+20 added-7 removed
3 unmodified lines4 from types import TracebackType5 6 import httpcore7 8+from .__version__ import __version__9 from ._auth import Auth, BasicAuth, FunctionAuth10 from ._config import (11 DEFAULT_LIMITS,12 DEFAULT_MAX_REDIRECTS,5 unmodified lines18 UnsetType,19 create_ssl_context,20 )21 from ._content_streams import ContentStream22+from ._decoders import SUPPORTED_DECODERS23 from ._exceptions import (24 HTTPCORE_EXC_MAP,25 InvalidURL,26 RemoteProtocolError,29 unmodified lines56 57 logger = get_logger(__name__)58 59 KEEPALIVE_EXPIRY = 5.060+USER_AGENT = f"python-httpx/{__version__}"61+ACCEPT_ENCODING = ", ".join(62+ [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]63+)64 65 66 class BaseClient:67 def __init__(11 unmodified lines79 self._base_url = self._enforce_trailing_slash(URL(base_url))80 81 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_env78 unmodified lines166 return self._headers167 168 @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_headers180 181 @property182 def cookies(self) -> Cookies:183 """129 unmodified lines313 """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 headers320 321 def _merge_queryparams(322 self, params: QueryParamTypes = None323 ) -> typing.Optional[QueryParamTypes]:1452 unmodified linesmodified:httpx/_models.py+5 added-28 removed
12 unmodified lines13 import chardet14 import rfc398615 import rfc3986.exceptions16 17-from .__version__ import __version__17 from ._content_streams import ByteStream, ContentStream, encode18 from ._decoders import (19 SUPPORTED_DECODERS,20 Decoder,80 unmodified lines101 return self._uri_reference.userinfo or ""102 103 @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])106 107 @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])110 111 @property112 def host(self) -> str:113 return self._uri_reference.host or ""462 unmodified lines576 warnings.warn(message, DeprecationWarning)577 return self.get_list(key, split_commas=split_commas)578 579 583-USER_AGENT = f"python-httpx/{__version__}"584-ACCEPT_ENCODING = ", ".join(585- [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]586-)587-588-580 class Request:581 def __init__(582 self,583 method: str,33 unmodified lines617 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.headers621 635- 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"))627 628 self.headers = Headers(auto_headers + self.headers.raw)629 630 @property608 unmodified linesmodified:tests/client/test_headers.py+22 added
122 unmodified lines123 }124 }125 126 127+def test_remove_default_header():128+ """129+ Remove a default header from the Client.130+ """131+ url = "http://example.org/echo_headers"132+133+ client = httpx.Client(transport=MockTransport())134+ del client.headers["User-Agent"]135+136+ response = client.get(url)137+138+ 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+ }147+148+149 def test_header_does_not_exist():150 headers = httpx.Headers({"foo": "bar"})151 with pytest.raises(KeyError):152 del headers["baz"]52 unmodified linesmodified:tests/models/test_requests.py+12 added
32 unmodified lines33 assert request.headers["Content-Type"] == "application/json"34 assert request.content == b'{"test": 123}'35 36 37+def test_headers():38+ request = httpx.Request("POST", "http://example.org", json={"test": 123})39+40+ assert request.headers == httpx.Headers(41+ {42+ "Host": "example.org",43+ "Content-Type": "application/json",44+ "Content-Length": "13",45+ }46+ )47+48+49 def 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