Skip to content
Myr

Move remaining utility functions from _utils.py to _models.py (#3387)

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

authored by RafaelWO · committed by GitHub · parent 6212e8f · Browse files · 5 files+118 added−124 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+118 added−124 removed

  • tests:+43 added−43 removed
  • other:+75 added−81 removed

5 files+118 added−124 removed

modified:httpx/_models.py+74 added-10 removed
1from __future__ import annotations23import codecs4import datetime5import email.message6import json as jsonlib7import re8import typing9import urllib.request10from collections.abc import Mapping11from http.cookiejar import Cookie, CookieJar
33 unmodified lines
45 ResponseExtensions,46 SyncByteStream,47)48from ._urls import URL47from ._utils import (48 is_known_encoding,49 obfuscate_sensitive_headers,50 parse_content_type_charset,51 parse_header_links,52)49from ._utils import to_bytes_or_str, to_str5051__all__ = ["Cookies", "Headers", "Request", "Response"]5253SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}545556def _is_known_encoding(encoding: str) -> bool:57 """58 Return `True` if `encoding` is a known codec.59 """60 try:61 codecs.lookup(encoding)62 except LookupError:63 return False64 return True656667def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes:68 """69 Coerce str/bytes into a strictly byte-wise HTTP header key.70 """
10 unmodified lines
81 raise TypeError(f"Header value must be str or bytes, not {type(value)}")82 return value.encode(encoding or "ascii")838485def _parse_content_type_charset(content_type: str) -> str | None:86 # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery.87 # See: https://peps.python.org/pep-0594/#cgi88 msg = email.message.Message()89 msg["content-type"] = content_type90 return msg.get_content_charset(failobj=None)919293def _parse_header_links(value: str) -> list[dict[str, str]]:94 """95 Returns a list of parsed link headers, for more info see:96 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link97 The generic syntax of those is:98 Link: < uri-reference >; param1=value1; param2="value2"99 So for instance:100 Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'101 would return102 [103 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},104 {"url": "http://.../back.jpeg"},105 ]106 :param value: HTTP Link entity-header field107 :return: list of parsed link headers108 """109 links: list[dict[str, str]] = []110 replace_chars = " '\""111 value = value.strip(replace_chars)112 if not value:113 return links114 for val in re.split(", *<", value):115 try:116 url, params = val.split(";", 1)117 except ValueError:118 url, params = val, ""119 link = {"url": url.strip("<> '\"")}120 for param in params.split(";"):121 try:122 key, value = param.split("=")123 except ValueError:124 break125 link[key.strip(replace_chars)] = value.strip(replace_chars)126 links.append(link)127 return links128129130def _obfuscate_sensitive_headers(131 items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]],132) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]:133 for k, v in items:134 if to_str(k.lower()) in SENSITIVE_HEADERS:135 v = to_bytes_or_str("[secure]", match_type_of=v)136 yield k, v137138139class Headers(typing.MutableMapping[str, str]):140 """141 HTTP headers, as a case-insensitive multi-dict.142 """
226 unmodified lines
369 encoding_str = ""370 if self.encoding != "ascii":371 encoding_str = f", encoding={self.encoding!r}"372309 as_list = list(obfuscate_sensitive_headers(self.multi_items()))373 as_list = list(_obfuscate_sensitive_headers(self.multi_items()))374 as_dict = dict(as_list)375376 no_duplicate_keys = len(as_dict) == len(as_list)377 if no_duplicate_keys:
284 unmodified lines
662 which enables charset autodetection.663 """664 if not hasattr(self, "_encoding"):665 encoding = self.charset_encoding602 if encoding is None or not is_known_encoding(encoding):666 if encoding is None or not _is_known_encoding(encoding):667 if isinstance(self.default_encoding, str):668 encoding = self.default_encoding669 elif hasattr(self, "_content"):670 encoding = self.default_encoding(self._content)
22 unmodified lines
693 content_type = self.headers.get("Content-Type")694 if content_type is None:695 return None696633 return parse_content_type_charset(content_type)697 return _parse_content_type_charset(content_type)698699 def _get_content_decoder(self) -> ContentDecoder:700 """701 Returns a decoder instance which can be used to decode the raw byte
146 unmodified lines
848 return {}849850 return {851 (link.get("rel") or link.get("url")): link788 for link in parse_header_links(header)852 for link in _parse_header_links(header)853 }854855 @property856 def num_bytes_downloaded(self) -> int:
421 unmodified lines
modified:httpx/_utils.py-70 removed
1from __future__ import annotations23import codecs4import email.message3import ipaddress4import os5import re6import typing
19 unmodified lines
26 return ""27 return str(value)282932def is_known_encoding(encoding: str) -> bool:33 """34 Return `True` if `encoding` is a known codec.35 """36 try:37 codecs.lookup(encoding)38 except LookupError:39 return False40 return True414243def parse_header_links(value: str) -> list[dict[str, str]]:44 """45 Returns a list of parsed link headers, for more info see:46 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link47 The generic syntax of those is:48 Link: < uri-reference >; param1=value1; param2="value2"49 So for instance:50 Link; '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;'51 would return52 [53 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},54 {"url": "http://.../back.jpeg"},55 ]56 :param value: HTTP Link entity-header field57 :return: list of parsed link headers58 """59 links: list[dict[str, str]] = []60 replace_chars = " '\""61 value = value.strip(replace_chars)62 if not value:63 return links64 for val in re.split(", *<", value):65 try:66 url, params = val.split(";", 1)67 except ValueError:68 url, params = val, ""69 link = {"url": url.strip("<> '\"")}70 for param in params.split(";"):71 try:72 key, value = param.split("=")73 except ValueError:74 break75 link[key.strip(replace_chars)] = value.strip(replace_chars)76 links.append(link)77 return links787980def parse_content_type_charset(content_type: str) -> str | None:81 # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery.82 # See: https://peps.python.org/pep-0594/#cgi83 msg = email.message.Message()84 msg["content-type"] = content_type85 return msg.get_content_charset(failobj=None)868788SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}899091def obfuscate_sensitive_headers(92 items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]],93) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]:94 for k, v in items:95 if to_str(k.lower()) in SENSITIVE_HEADERS:96 v = to_bytes_or_str("[secure]", match_type_of=v)97 yield k, v989930def port_or_default(url: URL) -> int | None:31 if url.port is not None:32 return url.port33 return {"http": 80, "https": 443}.get(url.scheme)
241 unmodified lines
modified:scripts/lint+1 added-1 removed
6 unmodified lines
7export SOURCE_FILES="httpx tests"89set -x1011${PREFIX}ruff --fix $SOURCE_FILES11${PREFIX}ruff check --fix $SOURCE_FILES12${PREFIX}ruff format $SOURCE_FILES
modified:tests/models/test_headers.py+43 added
172 unmodified lines
173 """174 value = "s3kr3t"175 h = httpx.Headers({header: value})176 assert repr(h) == "Headers({'%s': '[secure]'})" % header177178179@pytest.mark.parametrize(180 "headers, output",181 [182 ([("content-type", "text/html")], [("content-type", "text/html")]),183 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),184 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),185 ],186)187def test_obfuscate_sensitive_headers(headers, output):188 as_dict = {k: v for k, v in output}189 headers_class = httpx.Headers({k: v for k, v in headers})190 assert repr(headers_class) == f"Headers({as_dict!r})"191192193@pytest.mark.parametrize(194 "value, expected",195 (196 (197 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',198 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],199 ),200 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),201 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),202 (203 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',204 [205 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},206 {"url": "http://.../back.jpeg"},207 ],208 ),209 ("", []),210 ),211)212def test_parse_header_links(value, expected):213 all_links = httpx.Response(200, headers={"link": value}).links.values()214 assert all(link in all_links for link in expected)215216217def test_parse_header_links_no_link():218 all_links = httpx.Response(200).links219 assert all_links == {}
modified:tests/test_utils.py-43 removed
51 unmodified lines
52 response = httpx.Response(200, content=content)53 assert response.json() == {"abc": 123}545556@pytest.mark.parametrize(57 "value, expected",58 (59 (60 '<http:/.../front.jpeg>; rel=front; type="image/jpeg"',61 [{"url": "http:/.../front.jpeg", "rel": "front", "type": "image/jpeg"}],62 ),63 ("<http:/.../front.jpeg>", [{"url": "http:/.../front.jpeg"}]),64 ("<http:/.../front.jpeg>;", [{"url": "http:/.../front.jpeg"}]),65 (66 '<http:/.../front.jpeg>; type="image/jpeg",<http://.../back.jpeg>;',67 [68 {"url": "http:/.../front.jpeg", "type": "image/jpeg"},69 {"url": "http://.../back.jpeg"},70 ],71 ),72 ("", []),73 ),74)75def test_parse_header_links(value, expected):76 all_links = httpx.Response(200, headers={"link": value}).links.values()77 assert all(link in all_links for link in expected)787980def test_parse_header_links_no_link():81 all_links = httpx.Response(200).links82 assert all_links == {}838456def test_logging_request(server, caplog):57 caplog.set_level(logging.INFO)58 with httpx.Client() as client:59 response = client.get(server.url)
54 unmodified lines
114115 assert get_environment_proxies() == proxies116117147@pytest.mark.parametrize(148 "headers, output",149 [150 ([("content-type", "text/html")], [("content-type", "text/html")]),151 ([("authorization", "s3kr3t")], [("authorization", "[secure]")]),152 ([("proxy-authorization", "s3kr3t")], [("proxy-authorization", "[secure]")]),153 ],154)155def test_obfuscate_sensitive_headers(headers, output):156 as_dict = {k: v for k, v in output}157 headers_class = httpx.Headers({k: v for k, v in headers})158 assert repr(headers_class) == f"Headers({as_dict!r})"159160118def test_same_origin():119 origin = httpx.URL("https://example.com")120 request = httpx.Request("GET", "HTTPS://EXAMPLE.COM:443")121
88 unmodified lines