headers.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. from __future__ import annotations
  2. import collections.abc as cabc
  3. import re
  4. import typing as t
  5. from .._internal import _missing
  6. from ..exceptions import BadRequestKeyError
  7. from .mixins import ImmutableHeadersMixin
  8. from .structures import iter_multi_items
  9. from .structures import MultiDict
  10. if t.TYPE_CHECKING:
  11. import typing_extensions as te
  12. from _typeshed.wsgi import WSGIEnvironment
  13. T = t.TypeVar("T")
  14. class Headers:
  15. """An object that stores some headers. It has a dict-like interface,
  16. but is ordered, can store the same key multiple times, and iterating
  17. yields ``(key, value)`` pairs instead of only keys.
  18. This data structure is useful if you want a nicer way to handle WSGI
  19. headers which are stored as tuples in a list.
  20. From Werkzeug 0.3 onwards, the :exc:`KeyError` raised by this class is
  21. also a subclass of the :class:`~exceptions.BadRequest` HTTP exception
  22. and will render a page for a ``400 BAD REQUEST`` if caught in a
  23. catch-all for HTTP exceptions.
  24. Headers is mostly compatible with the Python :class:`wsgiref.headers.Headers`
  25. class, with the exception of `__getitem__`. :mod:`wsgiref` will return
  26. `None` for ``headers['missing']``, whereas :class:`Headers` will raise
  27. a :class:`KeyError`.
  28. To create a new ``Headers`` object, pass it a list, dict, or
  29. other ``Headers`` object with default values. These values are
  30. validated the same way values added later are.
  31. The header keys are assumed to be trusted and valid, they must not come
  32. from untrusted user input. Newlines in header values are not allowed and
  33. will raise a ``ValueError``.
  34. :param defaults: The list of default values for the :class:`Headers`.
  35. .. versionchanged:: 3.1
  36. Implement ``|`` and ``|=`` operators.
  37. .. versionchanged:: 2.1.0
  38. Default values are validated the same as values added later.
  39. .. versionchanged:: 0.9
  40. This data structure now stores unicode values similar to how the
  41. multi dicts do it. The main difference is that bytes can be set as
  42. well which will automatically be latin1 decoded.
  43. .. versionchanged:: 0.9
  44. The :meth:`linked` function was removed without replacement as it
  45. was an API that does not support the changes to the encoding model.
  46. """
  47. def __init__(
  48. self,
  49. defaults: (
  50. Headers
  51. | MultiDict[str, t.Any]
  52. | cabc.Mapping[str, t.Any | list[t.Any] | tuple[t.Any, ...] | set[t.Any]]
  53. | cabc.Iterable[tuple[str, t.Any]]
  54. | None
  55. ) = None,
  56. ) -> None:
  57. self._list: list[tuple[str, str]] = []
  58. if defaults is not None:
  59. self.extend(defaults)
  60. @t.overload
  61. def __getitem__(self, key: str) -> str: ...
  62. @t.overload
  63. def __getitem__(self, key: int) -> tuple[str, str]: ...
  64. @t.overload
  65. def __getitem__(self, key: slice) -> te.Self: ...
  66. def __getitem__(self, key: str | int | slice) -> str | tuple[str, str] | te.Self:
  67. if isinstance(key, str):
  68. return self._get_key(key)
  69. if isinstance(key, int):
  70. return self._list[key]
  71. return self.__class__(self._list[key])
  72. def _get_key(self, key: str) -> str:
  73. ikey = key.lower()
  74. for k, v in self._list:
  75. if k.lower() == ikey:
  76. return v
  77. raise BadRequestKeyError(key)
  78. def __eq__(self, other: object) -> bool:
  79. if other.__class__ is not self.__class__:
  80. return NotImplemented
  81. def lowered(item: tuple[str, ...]) -> tuple[str, ...]:
  82. return item[0].lower(), *item[1:]
  83. return set(map(lowered, other._list)) == set(map(lowered, self._list))
  84. __hash__ = None # type: ignore[assignment]
  85. @t.overload
  86. def get(self, key: str) -> str | None: ...
  87. @t.overload
  88. def get(self, key: str, default: str) -> str: ...
  89. @t.overload
  90. def get(self, key: str, default: T) -> str | T: ...
  91. @t.overload
  92. def get(self, key: str, type: cabc.Callable[[str], T]) -> T | None: ...
  93. @t.overload
  94. def get(self, key: str, default: T, type: cabc.Callable[[str], T]) -> T: ...
  95. def get( # type: ignore[misc]
  96. self,
  97. key: str,
  98. default: str | T | None = None,
  99. type: cabc.Callable[[str], T] | None = None,
  100. ) -> str | T | None:
  101. """Return the default value if the requested data doesn't exist.
  102. If `type` is provided and is a callable it should convert the value,
  103. return it or raise a :exc:`ValueError` if that is not possible. In
  104. this case the function will return the default as if the value was not
  105. found:
  106. >>> d = Headers([('Content-Length', '42')])
  107. >>> d.get('Content-Length', type=int)
  108. 42
  109. :param key: The key to be looked up.
  110. :param default: The default value to be returned if the key can't
  111. be looked up. If not further specified `None` is
  112. returned.
  113. :param type: A callable that is used to cast the value in the
  114. :class:`Headers`. If a :exc:`ValueError` is raised
  115. by this callable the default value is returned.
  116. .. versionchanged:: 3.0
  117. The ``as_bytes`` parameter was removed.
  118. .. versionchanged:: 0.9
  119. The ``as_bytes`` parameter was added.
  120. """
  121. try:
  122. rv = self._get_key(key)
  123. except KeyError:
  124. return default
  125. if type is None:
  126. return rv
  127. try:
  128. return type(rv)
  129. except ValueError:
  130. return default
  131. @t.overload
  132. def getlist(self, key: str) -> list[str]: ...
  133. @t.overload
  134. def getlist(self, key: str, type: cabc.Callable[[str], T]) -> list[T]: ...
  135. def getlist(
  136. self, key: str, type: cabc.Callable[[str], T] | None = None
  137. ) -> list[str] | list[T]:
  138. """Return the list of items for a given key. If that key is not in the
  139. :class:`Headers`, the return value will be an empty list. Just like
  140. :meth:`get`, :meth:`getlist` accepts a `type` parameter. All items will
  141. be converted with the callable defined there.
  142. :param key: The key to be looked up.
  143. :param type: A callable that is used to cast the value in the
  144. :class:`Headers`. If a :exc:`ValueError` is raised
  145. by this callable the value will be removed from the list.
  146. :return: a :class:`list` of all the values for the key.
  147. .. versionchanged:: 3.0
  148. The ``as_bytes`` parameter was removed.
  149. .. versionchanged:: 0.9
  150. The ``as_bytes`` parameter was added.
  151. """
  152. ikey = key.lower()
  153. if type is not None:
  154. result = []
  155. for k, v in self:
  156. if k.lower() == ikey:
  157. try:
  158. result.append(type(v))
  159. except ValueError:
  160. continue
  161. return result
  162. return [v for k, v in self if k.lower() == ikey]
  163. def get_all(self, name: str) -> list[str]:
  164. """Return a list of all the values for the named field.
  165. This method is compatible with the :mod:`wsgiref`
  166. :meth:`~wsgiref.headers.Headers.get_all` method.
  167. """
  168. return self.getlist(name)
  169. def items(self, lower: bool = False) -> t.Iterable[tuple[str, str]]:
  170. for key, value in self:
  171. if lower:
  172. key = key.lower()
  173. yield key, value
  174. def keys(self, lower: bool = False) -> t.Iterable[str]:
  175. for key, _ in self.items(lower):
  176. yield key
  177. def values(self) -> t.Iterable[str]:
  178. for _, value in self.items():
  179. yield value
  180. def extend(
  181. self,
  182. arg: (
  183. Headers
  184. | MultiDict[str, t.Any]
  185. | cabc.Mapping[str, t.Any | list[t.Any] | tuple[t.Any, ...] | set[t.Any]]
  186. | cabc.Iterable[tuple[str, t.Any]]
  187. | None
  188. ) = None,
  189. /,
  190. **kwargs: str,
  191. ) -> None:
  192. """Extend headers in this object with items from another object
  193. containing header items as well as keyword arguments.
  194. To replace existing keys instead of extending, use
  195. :meth:`update` instead.
  196. If provided, the first argument can be another :class:`Headers`
  197. object, a :class:`MultiDict`, :class:`dict`, or iterable of
  198. pairs.
  199. The header keys are assumed to be trusted and valid, they must not come
  200. from untrusted user input. Newlines in header values are not allowed and
  201. will raise a ``ValueError``.
  202. .. versionchanged:: 1.0
  203. Support :class:`MultiDict`. Allow passing ``kwargs``.
  204. """
  205. if arg is not None:
  206. for key, value in iter_multi_items(arg):
  207. self.add(key, value)
  208. for key, value in iter_multi_items(kwargs):
  209. self.add(key, value)
  210. def __delitem__(self, key: str | int | slice) -> None:
  211. if isinstance(key, str):
  212. self._del_key(key)
  213. return
  214. del self._list[key]
  215. def _del_key(self, key: str) -> None:
  216. key = key.lower()
  217. new = []
  218. for k, v in self._list:
  219. if k.lower() != key:
  220. new.append((k, v))
  221. self._list[:] = new
  222. def remove(self, key: str) -> None:
  223. """Remove a key.
  224. :param key: The key to be removed.
  225. """
  226. return self._del_key(key)
  227. @t.overload
  228. def pop(self) -> tuple[str, str]: ...
  229. @t.overload
  230. def pop(self, key: str) -> str: ...
  231. @t.overload
  232. def pop(self, key: int | None = ...) -> tuple[str, str]: ...
  233. @t.overload
  234. def pop(self, key: str, default: str) -> str: ...
  235. @t.overload
  236. def pop(self, key: str, default: T) -> str | T: ...
  237. def pop(
  238. self,
  239. key: str | int | None = None,
  240. default: str | T = _missing, # type: ignore[assignment]
  241. ) -> str | tuple[str, str] | T:
  242. """Removes and returns a key or index.
  243. :param key: The key to be popped. If this is an integer the item at
  244. that position is removed, if it's a string the value for
  245. that key is. If the key is omitted or `None` the last
  246. item is removed.
  247. :return: an item.
  248. """
  249. if key is None:
  250. return self._list.pop()
  251. if isinstance(key, int):
  252. return self._list.pop(key)
  253. try:
  254. rv = self._get_key(key)
  255. except KeyError:
  256. if default is not _missing:
  257. return default
  258. raise
  259. self.remove(key)
  260. return rv
  261. def popitem(self) -> tuple[str, str]:
  262. """Removes a key or index and returns a (key, value) item."""
  263. return self._list.pop()
  264. def __contains__(self, key: str) -> bool:
  265. """Check if a key is present."""
  266. try:
  267. self._get_key(key)
  268. except KeyError:
  269. return False
  270. return True
  271. def __iter__(self) -> t.Iterator[tuple[str, str]]:
  272. """Yield ``(key, value)`` tuples."""
  273. return iter(self._list)
  274. def __len__(self) -> int:
  275. return len(self._list)
  276. def add(self, key: str, value: t.Any, /, **kwargs: t.Any) -> None:
  277. """Add a new header tuple to the list.
  278. Keyword arguments can specify additional parameters for the header
  279. value, with underscores converted to dashes::
  280. >>> d = Headers()
  281. >>> d.add('Content-Type', 'text/plain')
  282. >>> d.add('Content-Disposition', 'attachment', filename='foo.png')
  283. The keyword argument dumping uses :func:`dump_options_header`
  284. behind the scenes.
  285. :param key: The header key. This is assumed to be trusted and valid, it
  286. must not come from untrusted user input.
  287. :param value: The header value. Newlines are not allowed and will raise
  288. a ``ValueError``.
  289. .. versionchanged:: 0.4.1
  290. keyword arguments were added for :mod:`wsgiref` compatibility.
  291. """
  292. if kwargs:
  293. value = _options_header_vkw(value, kwargs)
  294. value_str = _str_header_value(value)
  295. self._list.append((key, value_str))
  296. def add_header(self, key: str, value: t.Any, /, **kwargs: t.Any) -> None:
  297. """Add a new header tuple to the list.
  298. An alias for :meth:`add` for compatibility with the :mod:`wsgiref`
  299. :meth:`~wsgiref.headers.Headers.add_header` method.
  300. """
  301. self.add(key, value, **kwargs)
  302. def clear(self) -> None:
  303. """Clears all headers."""
  304. self._list.clear()
  305. def set(self, key: str, value: t.Any, /, **kwargs: t.Any) -> None:
  306. """Remove all header tuples for `key` and add a new one. The newly
  307. added key either appears at the end of the list if there was no
  308. entry or replaces the first one.
  309. Keyword arguments can specify additional parameters for the header
  310. value, with underscores converted to dashes. See :meth:`add` for
  311. more information.
  312. .. versionchanged:: 0.6.1
  313. :meth:`set` now accepts the same arguments as :meth:`add`.
  314. :param key: The header key. This is assumed to be trusted and valid, it
  315. must not come from untrusted user input.
  316. :param value: The header value. Newlines are not allowed and will raise
  317. a ``ValueError``.
  318. """
  319. if kwargs:
  320. value = _options_header_vkw(value, kwargs)
  321. value_str = _str_header_value(value)
  322. if not self._list:
  323. self._list.append((key, value_str))
  324. return
  325. iter_list = iter(self._list)
  326. ikey = key.lower()
  327. for idx, (old_key, _) in enumerate(iter_list):
  328. if old_key.lower() == ikey:
  329. # replace first occurrence
  330. self._list[idx] = (key, value_str)
  331. break
  332. else:
  333. # no existing occurrences
  334. self._list.append((key, value_str))
  335. return
  336. # remove remaining occurrences
  337. self._list[idx + 1 :] = [t for t in iter_list if t[0].lower() != ikey]
  338. def setlist(self, key: str, values: cabc.Iterable[t.Any]) -> None:
  339. """Remove any existing values for a header and add new ones.
  340. :param key: The header key. This is assumed to be trusted and valid, it
  341. must not come from untrusted user input.
  342. :param value: An iterable of header values. Newlines are not allowed and
  343. will raise a ``ValueError``.
  344. .. versionadded:: 1.0
  345. """
  346. if values:
  347. values_iter = iter(values)
  348. self.set(key, next(values_iter))
  349. for value in values_iter:
  350. self.add(key, value)
  351. else:
  352. self.remove(key)
  353. def setdefault(self, key: str, default: t.Any) -> str:
  354. """Return the first value for the key if it is in the headers,
  355. otherwise set the header to the value given by ``default`` and
  356. return that.
  357. :param key: The header key. This is assumed to be trusted and valid, it
  358. must not come from untrusted user input.
  359. :param default: The header value to set if the key is not present.
  360. Newlines are not allowed and will raise a ``ValueError``.
  361. """
  362. try:
  363. return self._get_key(key)
  364. except KeyError:
  365. pass
  366. self.set(key, default)
  367. return self._get_key(key)
  368. def setlistdefault(self, key: str, default: cabc.Iterable[t.Any]) -> list[str]:
  369. """Return the list of values for the key if it is in the
  370. headers, otherwise set the header to the list of values given
  371. by ``default`` and return that.
  372. Unlike :meth:`MultiDict.setlistdefault`, modifying the returned
  373. list will not affect the headers.
  374. :param key: The header key. This is assumed to be trusted and valid, it
  375. must not come from untrusted user input.
  376. :param default: An iterable of header values to set if the key is not
  377. present. Newlines are not allowed and will raise a ``ValueError``.
  378. .. versionadded:: 1.0
  379. """
  380. if key not in self:
  381. self.setlist(key, default)
  382. return self.getlist(key)
  383. @t.overload
  384. def __setitem__(self, key: str, value: t.Any) -> None: ...
  385. @t.overload
  386. def __setitem__(self, key: int, value: tuple[str, t.Any]) -> None: ...
  387. @t.overload
  388. def __setitem__(
  389. self, key: slice, value: cabc.Iterable[tuple[str, t.Any]]
  390. ) -> None: ...
  391. def __setitem__(
  392. self,
  393. key: str | int | slice,
  394. value: t.Any | tuple[str, t.Any] | cabc.Iterable[tuple[str, t.Any]],
  395. ) -> None:
  396. """Like :meth:`set` but also supports index/slice based setting."""
  397. if isinstance(key, str):
  398. self.set(key, value)
  399. elif isinstance(key, int):
  400. self._list[key] = value[0], _str_header_value(value[1]) # type: ignore[index]
  401. else:
  402. self._list[key] = [(k, _str_header_value(v)) for k, v in value] # type: ignore[str-unpack]
  403. def update(
  404. self,
  405. arg: (
  406. Headers
  407. | MultiDict[str, t.Any]
  408. | cabc.Mapping[
  409. str, t.Any | list[t.Any] | tuple[t.Any, ...] | cabc.Set[t.Any]
  410. ]
  411. | cabc.Iterable[tuple[str, t.Any]]
  412. | None
  413. ) = None,
  414. /,
  415. **kwargs: t.Any | list[t.Any] | tuple[t.Any, ...] | cabc.Set[t.Any],
  416. ) -> None:
  417. """Replace headers in this object with items from another
  418. headers object and keyword arguments.
  419. To extend existing keys instead of replacing, use :meth:`extend`
  420. instead.
  421. If provided, the first argument can be another :class:`Headers`
  422. object, a :class:`MultiDict`, :class:`dict`, or iterable of
  423. pairs.
  424. The header keys are assumed to be trusted and valid, they must not come
  425. from untrusted user input. Newlines in header values are not allowed and
  426. will raise a ``ValueError``.
  427. .. versionadded:: 1.0
  428. """
  429. if arg is not None:
  430. if isinstance(arg, (Headers, MultiDict)):
  431. for key in arg.keys():
  432. self.setlist(key, arg.getlist(key))
  433. elif isinstance(arg, cabc.Mapping):
  434. for key, value in arg.items():
  435. if isinstance(value, (list, tuple, set)):
  436. self.setlist(key, value)
  437. else:
  438. self.set(key, value)
  439. else:
  440. for key, value in arg:
  441. self.set(key, value)
  442. for key, value in kwargs.items():
  443. if isinstance(value, (list, tuple, set)):
  444. self.setlist(key, value)
  445. else:
  446. self.set(key, value)
  447. def __or__(
  448. self,
  449. other: cabc.Mapping[
  450. str, t.Any | list[t.Any] | tuple[t.Any, ...] | cabc.Set[t.Any]
  451. ],
  452. ) -> te.Self:
  453. if not isinstance(other, cabc.Mapping):
  454. return NotImplemented
  455. rv = self.copy()
  456. rv.update(other)
  457. return rv
  458. def __ior__(
  459. self,
  460. other: (
  461. cabc.Mapping[str, t.Any | list[t.Any] | tuple[t.Any, ...] | cabc.Set[t.Any]]
  462. | cabc.Iterable[tuple[str, t.Any]]
  463. ),
  464. ) -> te.Self:
  465. if not isinstance(other, (cabc.Mapping, cabc.Iterable)):
  466. return NotImplemented
  467. self.update(other)
  468. return self
  469. def to_wsgi_list(self) -> list[tuple[str, str]]:
  470. """Convert the headers into a list suitable for WSGI.
  471. :return: list
  472. """
  473. return list(self)
  474. def copy(self) -> te.Self:
  475. return self.__class__(self._list)
  476. def __copy__(self) -> te.Self:
  477. return self.copy()
  478. def __str__(self) -> str:
  479. """Returns formatted headers suitable for HTTP transmission."""
  480. strs = []
  481. for key, value in self.to_wsgi_list():
  482. strs.append(f"{key}: {value}")
  483. strs.append("\r\n")
  484. return "\r\n".join(strs)
  485. def __repr__(self) -> str:
  486. return f"{type(self).__name__}({list(self)!r})"
  487. def _options_header_vkw(value: str, kw: dict[str, t.Any]) -> str:
  488. return http.dump_options_header(
  489. value, {k.replace("_", "-"): v for k, v in kw.items()}
  490. )
  491. _newline_re = re.compile(r"[\r\n]")
  492. def _str_header_value(value: t.Any) -> str:
  493. if not isinstance(value, str):
  494. value = str(value)
  495. if _newline_re.search(value) is not None:
  496. raise ValueError("Header values must not contain newline characters.")
  497. return value # type: ignore[no-any-return]
  498. class EnvironHeaders(ImmutableHeadersMixin, Headers): # type: ignore[misc]
  499. """Read only version of the headers from a WSGI environment. This
  500. provides the same interface as `Headers` and is constructed from
  501. a WSGI environment.
  502. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a
  503. subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will
  504. render a page for a ``400 BAD REQUEST`` if caught in a catch-all for
  505. HTTP exceptions.
  506. """
  507. def __init__(self, environ: WSGIEnvironment) -> None:
  508. super().__init__()
  509. self.environ = environ
  510. def __eq__(self, other: object) -> bool:
  511. if not isinstance(other, EnvironHeaders):
  512. return NotImplemented
  513. return self.environ is other.environ
  514. __hash__ = None
  515. def __getitem__(self, key: str) -> str: # type: ignore[override]
  516. return self._get_key(key)
  517. def _get_key(self, key: str) -> str:
  518. if not isinstance(key, str):
  519. raise BadRequestKeyError(key)
  520. key = key.upper().replace("-", "_")
  521. if key in {"CONTENT_TYPE", "CONTENT_LENGTH"}:
  522. return self.environ[key] # type: ignore[no-any-return]
  523. return self.environ[f"HTTP_{key}"] # type: ignore[no-any-return]
  524. def __len__(self) -> int:
  525. return sum(1 for _ in self)
  526. def __iter__(self) -> cabc.Iterator[tuple[str, str]]:
  527. for key, value in self.environ.items():
  528. if key.startswith("HTTP_") and key not in {
  529. "HTTP_CONTENT_TYPE",
  530. "HTTP_CONTENT_LENGTH",
  531. }:
  532. yield key[5:].replace("_", "-").title(), value
  533. elif key in {"CONTENT_TYPE", "CONTENT_LENGTH"} and value:
  534. yield key.replace("_", "-").title(), value
  535. def copy(self) -> t.NoReturn:
  536. raise TypeError(f"cannot create {type(self).__name__!r} copies")
  537. def __or__(self, other: t.Any) -> t.NoReturn:
  538. raise TypeError(f"cannot create {type(self).__name__!r} copies")
  539. # circular dependencies
  540. from .. import http # noqa: E402