Preserve header casing (#1338)
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 0eed6a3 · Browse files · 3 files·+97 added−48 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+97 added−48 removed
- tests:+29 added−0 removed
- other:+68 added−48 removed
Provenance
- Commit
c725387- Tree
29ec887- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
0eed6a3
3 files changed+97 added−48 removed
modified:httpx/_models.py+60 added-45 removed
523 unmodified lines524 """525 526 def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:527 if headers is None:528- self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]528+ self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]]529 elif isinstance(headers, Headers):530- self._list = list(headers.raw)530+ self._list = list(headers._list)531 elif isinstance(headers, dict):532 self._list = [533- (normalize_header_key(k, encoding), normalize_header_value(v, encoding))533+ (534+ normalize_header_key(k, lower=False, encoding=encoding),535+ normalize_header_key(k, lower=True, encoding=encoding),536+ normalize_header_value(v, encoding),537+ )538 for k, v in headers.items()539 ]540 else:541 self._list = [538- (normalize_header_key(k, encoding), normalize_header_value(v, encoding))542+ (543+ normalize_header_key(k, lower=False, encoding=encoding),544+ normalize_header_key(k, lower=True, encoding=encoding),545+ normalize_header_value(v, encoding),546+ )547 for k, v in headers548 ]549 542- self._dict = {} # type: typing.Dict[bytes, bytes]543- for key, value in self._list:544- if key in self._dict:545- self._dict[key] = self._dict[key] + b", " + value546- else:547- self._dict[key] = value548-550 self._encoding = encoding551 552 @property553 def encoding(self) -> str:28 unmodified lines582 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:583 """584 Returns a list of the raw header items, as byte pairs.585 """585- return list(self._list)586+ return [(raw_key, value) for raw_key, _, value in self._list]587 588 def keys(self) -> typing.KeysView[str]:588- return {key.decode(self.encoding): None for key in self._dict.keys()}.keys()589+ return {key.decode(self.encoding): None for _, key, value in self._list}.keys()590 591 def values(self) -> typing.ValuesView[str]:591- return {592- key: value.decode(self.encoding) for key, value in self._dict.items()593- }.values()592+ values_dict: typing.Dict[str, str] = {}593+ for _, key, value in self._list:594+ str_key = key.decode(self.encoding)595+ str_value = value.decode(self.encoding)596+ if str_key in values_dict:597+ values_dict[str_key] += f", {str_value}"598+ else:599+ values_dict[str_key] = str_value600+ return values_dict.values()601 602 def items(self) -> typing.ItemsView[str, str]:603 """604 Return `(key, value)` items of headers. Concatenate headers605 into a single comma seperated value when a key occurs multiple times.606 """600- return {601- key.decode(self.encoding): value.decode(self.encoding)602- for key, value in self._dict.items()603- }.items()607+ values_dict: typing.Dict[str, str] = {}608+ for _, key, value in self._list:609+ str_key = key.decode(self.encoding)610+ str_value = value.decode(self.encoding)611+ if str_key in values_dict:612+ values_dict[str_key] += f", {str_value}"613+ else:614+ values_dict[str_key] = str_value615+ return values_dict.items()616 617 def multi_items(self) -> typing.List[typing.Tuple[str, str]]:618 """619 Return a list of `(key, value)` pairs of headers. Allow multiple1 unmodified line621 comma seperated value.622 """623 return [624 (key.decode(self.encoding), value.decode(self.encoding))613- for key, value in self._list625+ for _, key, value in self._list626 ]627 628 def get(self, key: str, default: typing.Any = None) -> typing.Any:629 """14 unmodified lines644 get_header_key = key.lower().encode(self.encoding)645 646 values = [647 item_value.decode(self.encoding)636- for item_key, item_value in self._list637- if item_key == get_header_key648+ for _, item_key, item_value in self._list649+ if item_key.lower() == get_header_key650 ]651 652 if not split_commas:653 return values4 unmodified lines658 return split_values659 660 def update(self, headers: HeaderTypes = None) -> None: # type: ignore661 headers = Headers(headers)650- for header in headers:651- self[header] = headers[header]662+ for key, value in headers.raw:663+ self[key.decode(headers.encoding)] = value.decode(headers.encoding)664 665 def copy(self) -> "Headers":654- return Headers(dict(self.items()), encoding=self.encoding)666+ return Headers(self, encoding=self.encoding)667 668 def __getitem__(self, key: str) -> str:669 """670 Return a single header value.3 unmodified lines674 """675 normalized_key = key.lower().encode(self.encoding)676 677 items = []666- for header_key, header_value in self._list:678+ for _, header_key, header_value in self._list:679 if header_key == normalized_key:680 items.append(header_value.decode(self.encoding))681 682 if items:5 unmodified lines688 """689 Set the header `key` to `value`, removing any duplicate entries.690 Retains insertion order.691 """680- set_key = key.lower().encode(self._encoding or "utf-8")692+ set_key = key.encode(self._encoding or "utf-8")693 set_value = value.encode(self._encoding or "utf-8")694+ lookup_key = set_key.lower()695 683- self._dict[set_key] = set_value684-696 found_indexes = []686- for idx, (item_key, _) in enumerate(self._list):687- if item_key == set_key:697+ for idx, (_, item_key, _) in enumerate(self._list):698+ if item_key == lookup_key:699 found_indexes.append(idx)700 701 for idx in reversed(found_indexes[1:]):702 del self._list[idx]703 704 if found_indexes:705 idx = found_indexes[0]695- self._list[idx] = (set_key, set_value)706+ self._list[idx] = (set_key, lookup_key, set_value)707 else:697- self._list.append((set_key, set_value))708+ self._list.append((set_key, lookup_key, set_value))709 710 def __delitem__(self, key: str) -> None:711 """712 Remove the header `key`.713 """714 del_key = key.lower().encode(self.encoding)715 705- del self._dict[del_key]706-716 pop_indexes = []708- for idx, (item_key, _) in enumerate(self._list):709- if item_key == del_key:717+ for idx, (_, item_key, _) in enumerate(self._list):718+ if item_key.lower() == del_key:719 pop_indexes.append(idx)720 721+ if not pop_indexes:722+ raise KeyError(key)723+724 for idx in reversed(pop_indexes):725 del self._list[idx]726 727 def __contains__(self, key: typing.Any) -> bool:728 header_key = key.lower().encode(self.encoding)717- return header_key in self._dict729+ return header_key in [key for _, key, _ in self._list]730 731 def __iter__(self) -> typing.Iterator[typing.Any]:732 return iter(self.keys())733 4 unmodified lines738 try:739 other_headers = Headers(other)740 except ValueError:741 return False730- return sorted(self._list) == sorted(other_headers._list)742 743+ self_list = [(key, value) for _, key, value in self._list]744+ other_list = [(key, value) for _, key, value in other_headers._list]745+ return sorted(self_list) == sorted(other_list)746+747 def __repr__(self) -> str:748 class_name = self.__class__.__name__749 750 encoding_str = ""56 unmodified lines807 808 def _prepare(self, default_headers: typing.Dict[str, str]) -> None:809 for key, value in default_headers.items():810 # Ignore Transfer-Encoding if the Content-Length has been set explicitly.796- if key.lower() == "transfer-encoding" and "content-length" in self.headers:811+ if key.lower() == "transfer-encoding" and "Content-Length" in self.headers:812 continue813 self.headers.setdefault(key, value)814 815 auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []816 802- has_host = "host" in self.headers817+ has_host = "Host" in self.headers818 has_content_length = (804- "content-length" in self.headers or "transfer-encoding" in self.headers819+ "Content-Length" in self.headers or "Transfer-Encoding" in self.headers820 )821 822 if not has_host and self.url.host:823 default_port = {"http": 80, "https": 443}.get(self.url.scheme)824 if self.url.port is None or self.url.port == default_port:825 host_header = self.url.host.encode("ascii")826 else:827 host_header = self.url.netloc.encode("ascii")813- auto_headers.append((b"host", host_header))828+ auto_headers.append((b"Host", host_header))829 if not has_content_length and self.method in ("POST", "PUT", "PATCH"):815- auto_headers.append((b"content-length", b"0"))830+ auto_headers.append((b"Content-Length", b"0"))831 832 self.headers = Headers(auto_headers + self.headers.raw)833 834 @property627 unmodified linesmodified:httpx/_utils.py+8 added-3 removed
28 unmodified lines29 )30 31 32 def normalize_header_key(33- value: typing.Union[str, bytes], encoding: str = None33+ value: typing.Union[str, bytes],34+ lower: bool,35+ encoding: str = None,36 ) -> bytes:37 """38 Coerce str/bytes into a strictly byte-wise HTTP header key.39 """40 if isinstance(value, bytes):39- return value.lower()40- return value.encode(encoding or "ascii").lower()41+ bytes_value = value42+ else:43+ bytes_value = value.encode(encoding or "ascii")44 45+ return bytes_value.lower() if lower else bytes_value46 47+48 def normalize_header_value(49 value: typing.Union[str, bytes], encoding: str = None50 ) -> bytes:51 """490 unmodified linesmodified:tests/client/test_client.py+29 added
269 unmodified lines270 271 assert client.is_closed272 with pytest.raises(RuntimeError):273 client.get("http://example.com")274+275+276+def echo_raw_headers(request: httpx.Request) -> httpx.Response:277+ data = [278+ (name.decode("ascii"), value.decode("ascii"))279+ for name, value in request.headers.raw280+ ]281+ return httpx.Response(200, json=data)282+283+284+def test_raw_client_header():285+ """286+ Set a header in the Client.287+ """288+ url = "http://example.org/echo_headers"289+ headers = {"Example-Header": "example-value"}290+291+ client = httpx.Client(transport=MockTransport(echo_raw_headers), headers=headers)292+ response = client.get(url)293+294+ assert response.status_code == 200295+ assert response.json() == [296+ ["Host", "example.org"],297+ ["Accept", "*/*"],298+ ["Accept-Encoding", "gzip, deflate, br"],299+ ["Connection", "keep-alive"],300+ ["User-Agent", f"python-httpx/{httpx.__version__}"],301+ ["Example-Header", "example-value"],302+ ]