4646from ._urls import URL
4747from ._utils import (
4848 is_known_encoding ,
49- normalize_header_key ,
50- normalize_header_value ,
5149 obfuscate_sensitive_headers ,
5250 parse_content_type_charset ,
5351 parse_header_links ,
5654__all__ = ["Cookies" , "Headers" , "Request" , "Response" ]
5755
5856
57+ def _normalize_header_key (key : str | bytes , encoding : str | None = None ) -> bytes :
58+ """
59+ Coerce str/bytes into a strictly byte-wise HTTP header key.
60+ """
61+ return key if isinstance (key , bytes ) else key .encode (encoding or "ascii" )
62+
63+
64+ def _normalize_header_value (value : str | bytes , encoding : str | None = None ) -> bytes :
65+ """
66+ Coerce str/bytes into a strictly byte-wise HTTP header value.
67+ """
68+ if isinstance (value , bytes ):
69+ return value
70+ if not isinstance (value , str ):
71+ raise TypeError (f"Header value must be str or bytes, not { type (value )} " )
72+ return value .encode (encoding or "ascii" )
73+
74+
5975class Headers (typing .MutableMapping [str , str ]):
6076 """
6177 HTTP headers, as a case-insensitive multi-dict.
@@ -66,28 +82,20 @@ def __init__(
6682 headers : HeaderTypes | None = None ,
6783 encoding : str | None = None ,
6884 ) -> None :
69- if headers is None :
70- self . _list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]]
71- elif isinstance (headers , Headers ):
85+ self . _list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]]
86+
87+ if isinstance (headers , Headers ):
7288 self ._list = list (headers ._list )
7389 elif isinstance (headers , Mapping ):
74- self ._list = [
75- (
76- normalize_header_key (k , lower = False , encoding = encoding ),
77- normalize_header_key (k , lower = True , encoding = encoding ),
78- normalize_header_value (v , encoding ),
79- )
80- for k , v in headers .items ()
81- ]
82- else :
83- self ._list = [
84- (
85- normalize_header_key (k , lower = False , encoding = encoding ),
86- normalize_header_key (k , lower = True , encoding = encoding ),
87- normalize_header_value (v , encoding ),
88- )
89- for k , v in headers
90- ]
90+ for k , v in headers .items ():
91+ bytes_key = _normalize_header_key (k , encoding )
92+ bytes_value = _normalize_header_value (v , encoding )
93+ self ._list .append ((bytes_key , bytes_key .lower (), bytes_value ))
94+ elif headers is not None :
95+ for k , v in headers :
96+ bytes_key = _normalize_header_key (k , encoding )
97+ bytes_value = _normalize_header_value (v , encoding )
98+ self ._list .append ((bytes_key , bytes_key .lower (), bytes_value ))
9199
92100 self ._encoding = encoding
93101
0 commit comments