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
Provenance
- Commit
41597ad- Tree
6ec9b2c- Author
RafaelWO <38643099+RafaelWO@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
6212e8f
5 files changed+118 added−124 removed
modified:httpx/_models.py+74 added-10 removed
1 from __future__ import annotations2 3+import codecs4 import datetime5 import email.message6 import json as jsonlib7+import re8 import typing9 import urllib.request10 from collections.abc import Mapping11 from http.cookiejar import Cookie, CookieJar33 unmodified lines45 ResponseExtensions,46 SyncByteStream,47 )48 from ._urls import URL47-from ._utils import (48- is_known_encoding,49- obfuscate_sensitive_headers,50- parse_content_type_charset,51- parse_header_links,52-)49+from ._utils import to_bytes_or_str, to_str50 51 __all__ = ["Cookies", "Headers", "Request", "Response"]52 53+SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}54 55+56+def _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 True65+66+67 def _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 lines81 raise TypeError(f"Header value must be str or bytes, not {type(value)}")82 return value.encode(encoding or "ascii")83 84 85+def _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)91+92+93+def _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 links128+129+130+def _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, v137+138+139 class Headers(typing.MutableMapping[str, str]):140 """141 HTTP headers, as a case-insensitive multi-dict.142 """226 unmodified lines369 encoding_str = ""370 if self.encoding != "ascii":371 encoding_str = f", encoding={self.encoding!r}"372 309- 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)375 376 no_duplicate_keys = len(as_dict) == len(as_list)377 if no_duplicate_keys:284 unmodified lines662 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 lines693 content_type = self.headers.get("Content-Type")694 if content_type is None:695 return None696 633- return parse_content_type_charset(content_type)697+ return _parse_content_type_charset(content_type)698 699 def _get_content_decoder(self) -> ContentDecoder:700 """701 Returns a decoder instance which can be used to decode the raw byte146 unmodified lines848 return {}849 850 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 }854 855 @property856 def num_bytes_downloaded(self) -> int:421 unmodified linesmodified:httpx/_utils.py-70 removed
1 from __future__ import annotations2 3-import codecs4-import email.message3 import ipaddress4 import os5 import re6 import typing19 unmodified lines26 return ""27 return str(value)28 29 32-def 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 True41-42-43-def 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 links78-79-80-def 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)86-87-88-SENSITIVE_HEADERS = {"authorization", "proxy-authorization"}89-90-91-def 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, v98-99-30 def 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 linesmodified:scripts/lint+1 added-1 removed
6 unmodified lines7 export SOURCE_FILES="httpx tests"8 9 set -x10 11-${PREFIX}ruff --fix $SOURCE_FILES11+${PREFIX}ruff check --fix $SOURCE_FILES12 ${PREFIX}ruff format $SOURCE_FILESmodified:tests/models/test_headers.py+43 added
172 unmodified lines173 """174 value = "s3kr3t"175 h = httpx.Headers({header: value})176 assert repr(h) == "Headers({'%s': '[secure]'})" % header177+178+179+@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+)187+def 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})"191+192+193+@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+)212+def 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)215+216+217+def 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 lines52 response = httpx.Response(200, content=content)53 assert response.json() == {"abc": 123}54 55 56-@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-)75-def 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)78-79-80-def test_parse_header_links_no_link():81- all_links = httpx.Response(200).links82- assert all_links == {}83-84-56 def 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 lines114 115 assert get_environment_proxies() == proxies116 117 147-@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-)155-def 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})"159-160-118 def test_same_origin():119 origin = httpx.URL("https://example.com")120 request = httpx.Request("GET", "HTTPS://EXAMPLE.COM:443")121 88 unmodified lines