11from __future__ import annotations
22
3+ import re
34from collections .abc import Iterable , Iterator , Mapping , MutableMapping
45from typing import Any , Protocol
56
@@ -24,6 +25,10 @@ def __str__(self) -> str:
2425 return super ().__str__ ()
2526
2627
28+ # Obsolete line folding for header values is not supported.
29+ is_valid_header_value = re .compile (r"[\x09\x20-\x7e\x80-\xff]*" ).fullmatch
30+
31+
2732class Headers (MutableMapping [str , str ]):
2833 """
2934 Efficient data structure for manipulating HTTP headers.
@@ -107,6 +112,8 @@ def __getitem__(self, key: str) -> str:
107112 raise MultipleValuesError (key )
108113
109114 def __setitem__ (self , key : str , value : str ) -> None :
115+ if not is_valid_header_value (str (value )):
116+ raise InvalidHeaderValue (value )
110117 self ._dict .setdefault (key .lower (), []).append (value )
111118 self ._list .append ((key , value ))
112119
@@ -181,3 +188,7 @@ def __getitem__(self, key: str) -> str: ...
181188keys and values are :class:`str`.
182189
183190"""
191+
192+
193+ # At the bottom to break an import cycle.
194+ from .exceptions import InvalidHeaderValue # noqa: E402
0 commit comments