http.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  1. from __future__ import annotations
  2. import email.utils
  3. import re
  4. import typing as t
  5. import warnings
  6. from datetime import date
  7. from datetime import datetime
  8. from datetime import time
  9. from datetime import timedelta
  10. from datetime import timezone
  11. from enum import Enum
  12. from hashlib import sha1
  13. from time import mktime
  14. from time import struct_time
  15. from urllib.parse import quote
  16. from urllib.parse import unquote
  17. from ._internal import _dt_as_utc
  18. from ._internal import _plain_int
  19. if t.TYPE_CHECKING:
  20. from _typeshed.wsgi import WSGIEnvironment
  21. _token_chars = frozenset(
  22. "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"
  23. )
  24. _etag_re = re.compile(r'([Ww]/)?(?:"(.*?)"|(.*?))(?:\s*,\s*|$)')
  25. _entity_headers = frozenset(
  26. [
  27. "allow",
  28. "content-encoding",
  29. "content-language",
  30. "content-length",
  31. "content-location",
  32. "content-md5",
  33. "content-range",
  34. "content-type",
  35. "expires",
  36. "last-modified",
  37. ]
  38. )
  39. _hop_by_hop_headers = frozenset(
  40. [
  41. "connection",
  42. "keep-alive",
  43. "proxy-authenticate",
  44. "proxy-authorization",
  45. "te",
  46. "trailer",
  47. "transfer-encoding",
  48. "upgrade",
  49. ]
  50. )
  51. HTTP_STATUS_CODES = {
  52. 100: "Continue",
  53. 101: "Switching Protocols",
  54. 102: "Processing",
  55. 103: "Early Hints", # see RFC 8297
  56. 200: "OK",
  57. 201: "Created",
  58. 202: "Accepted",
  59. 203: "Non Authoritative Information",
  60. 204: "No Content",
  61. 205: "Reset Content",
  62. 206: "Partial Content",
  63. 207: "Multi Status",
  64. 208: "Already Reported", # see RFC 5842
  65. 226: "IM Used", # see RFC 3229
  66. 300: "Multiple Choices",
  67. 301: "Moved Permanently",
  68. 302: "Found",
  69. 303: "See Other",
  70. 304: "Not Modified",
  71. 305: "Use Proxy",
  72. 306: "Switch Proxy", # unused
  73. 307: "Temporary Redirect",
  74. 308: "Permanent Redirect",
  75. 400: "Bad Request",
  76. 401: "Unauthorized",
  77. 402: "Payment Required", # unused
  78. 403: "Forbidden",
  79. 404: "Not Found",
  80. 405: "Method Not Allowed",
  81. 406: "Not Acceptable",
  82. 407: "Proxy Authentication Required",
  83. 408: "Request Timeout",
  84. 409: "Conflict",
  85. 410: "Gone",
  86. 411: "Length Required",
  87. 412: "Precondition Failed",
  88. 413: "Request Entity Too Large",
  89. 414: "Request URI Too Long",
  90. 415: "Unsupported Media Type",
  91. 416: "Requested Range Not Satisfiable",
  92. 417: "Expectation Failed",
  93. 418: "I'm a teapot", # see RFC 2324
  94. 421: "Misdirected Request", # see RFC 7540
  95. 422: "Unprocessable Entity",
  96. 423: "Locked",
  97. 424: "Failed Dependency",
  98. 425: "Too Early", # see RFC 8470
  99. 426: "Upgrade Required",
  100. 428: "Precondition Required", # see RFC 6585
  101. 429: "Too Many Requests",
  102. 431: "Request Header Fields Too Large",
  103. 449: "Retry With", # proprietary MS extension
  104. 451: "Unavailable For Legal Reasons",
  105. 500: "Internal Server Error",
  106. 501: "Not Implemented",
  107. 502: "Bad Gateway",
  108. 503: "Service Unavailable",
  109. 504: "Gateway Timeout",
  110. 505: "HTTP Version Not Supported",
  111. 506: "Variant Also Negotiates", # see RFC 2295
  112. 507: "Insufficient Storage",
  113. 508: "Loop Detected", # see RFC 5842
  114. 510: "Not Extended",
  115. 511: "Network Authentication Failed",
  116. }
  117. class COEP(Enum):
  118. """Cross Origin Embedder Policies"""
  119. UNSAFE_NONE = "unsafe-none"
  120. REQUIRE_CORP = "require-corp"
  121. class COOP(Enum):
  122. """Cross Origin Opener Policies"""
  123. UNSAFE_NONE = "unsafe-none"
  124. SAME_ORIGIN_ALLOW_POPUPS = "same-origin-allow-popups"
  125. SAME_ORIGIN = "same-origin"
  126. def quote_header_value(value: t.Any, allow_token: bool = True) -> str:
  127. """Add double quotes around a header value. If the header contains only ASCII token
  128. characters, it will be returned unchanged. If the header contains ``"`` or ``\\``
  129. characters, they will be escaped with an additional ``\\`` character.
  130. This is the reverse of :func:`unquote_header_value`.
  131. :param value: The value to quote. Will be converted to a string.
  132. :param allow_token: Disable to quote the value even if it only has token characters.
  133. .. versionchanged:: 3.0
  134. Passing bytes is not supported.
  135. .. versionchanged:: 3.0
  136. The ``extra_chars`` parameter is removed.
  137. .. versionchanged:: 2.3
  138. The value is quoted if it is the empty string.
  139. .. versionadded:: 0.5
  140. """
  141. value_str = str(value)
  142. if not value_str:
  143. return '""'
  144. if allow_token:
  145. token_chars = _token_chars
  146. if token_chars.issuperset(value_str):
  147. return value_str
  148. value_str = value_str.replace("\\", "\\\\").replace('"', '\\"')
  149. return f'"{value_str}"'
  150. _unslash_re = re.compile(r"\\(.)", re.A)
  151. def unquote_header_value(value: str) -> str:
  152. """Remove double quotes and backslash escapes from a header value.
  153. This is the reverse of :func:`quote_header_value`.
  154. :param value: The header value to unquote.
  155. .. versionchanged:: 3.2
  156. Removes escape preceding any character.
  157. .. versionchanged:: 3.0
  158. The ``is_filename`` parameter is removed.
  159. """
  160. if len(value) >= 2 and value[0] == value[-1] == '"':
  161. return _unslash_re.sub(r"\g<1>", value[1:-1])
  162. return value
  163. def dump_options_header(header: str | None, options: t.Mapping[str, t.Any]) -> str:
  164. """Produce a header value and ``key=value`` parameters separated by semicolons
  165. ``;``. For example, the ``Content-Type`` header.
  166. .. code-block:: python
  167. dump_options_header("text/html", {"charset": "UTF-8"})
  168. 'text/html; charset=UTF-8'
  169. This is the reverse of :func:`parse_options_header`.
  170. If a value contains non-token characters, it will be quoted.
  171. If a value is ``None``, the parameter is skipped.
  172. In some keys for some headers, a UTF-8 value can be encoded using a special
  173. ``key*=UTF-8''value`` form, where ``value`` is percent encoded. This function will
  174. not produce that format automatically, but if a given key ends with an asterisk
  175. ``*``, the value is assumed to have that form and will not be quoted further.
  176. :param header: The primary header value.
  177. :param options: Parameters to encode as ``key=value`` pairs.
  178. .. versionchanged:: 2.3
  179. Keys with ``None`` values are skipped rather than treated as a bare key.
  180. .. versionchanged:: 2.2.3
  181. If a key ends with ``*``, its value will not be quoted.
  182. """
  183. segments = []
  184. if header is not None:
  185. segments.append(header)
  186. for key, value in options.items():
  187. if value is None:
  188. continue
  189. if key[-1] == "*":
  190. segments.append(f"{key}={value}")
  191. else:
  192. segments.append(f"{key}={quote_header_value(value)}")
  193. return "; ".join(segments)
  194. def dump_header(iterable: dict[str, t.Any] | t.Iterable[t.Any]) -> str:
  195. """Produce a header value from a list of items or ``key=value`` pairs, separated by
  196. commas ``,``.
  197. This is the reverse of :func:`parse_list_header`, :func:`parse_dict_header`, and
  198. :func:`parse_set_header`.
  199. If a value contains non-token characters, it will be quoted.
  200. If a value is ``None``, the key is output alone.
  201. In some keys for some headers, a UTF-8 value can be encoded using a special
  202. ``key*=UTF-8''value`` form, where ``value`` is percent encoded. This function will
  203. not produce that format automatically, but if a given key ends with an asterisk
  204. ``*``, the value is assumed to have that form and will not be quoted further.
  205. .. code-block:: python
  206. dump_header(["foo", "bar baz"])
  207. 'foo, "bar baz"'
  208. dump_header({"foo": "bar baz"})
  209. 'foo="bar baz"'
  210. :param iterable: The items to create a header from.
  211. .. versionchanged:: 3.0
  212. The ``allow_token`` parameter is removed.
  213. .. versionchanged:: 2.2.3
  214. If a key ends with ``*``, its value will not be quoted.
  215. """
  216. if isinstance(iterable, dict):
  217. items = []
  218. for key, value in iterable.items():
  219. if value is None:
  220. items.append(key)
  221. elif key[-1] == "*":
  222. items.append(f"{key}={value}")
  223. else:
  224. items.append(f"{key}={quote_header_value(value)}")
  225. else:
  226. items = [quote_header_value(x) for x in iterable]
  227. return ", ".join(items)
  228. def dump_csp_header(header: ds.ContentSecurityPolicy) -> str:
  229. """Dump a Content Security Policy header.
  230. These are structured into policies such as "default-src 'self';
  231. script-src 'self'".
  232. .. versionadded:: 1.0.0
  233. Support for Content Security Policy headers was added.
  234. """
  235. return "; ".join(f"{key} {value}" for key, value in header.items())
  236. def parse_list_header(value: str) -> list[str]:
  237. """Parse a header value that consists of a list of comma separated items according
  238. to `RFC 9110 <https://httpwg.org/specs/rfc9110.html#abnf.extension>`__.
  239. Surrounding quotes are removed from items, but internal quotes are left for
  240. future parsing. Empty values are discarded.
  241. .. code-block:: python
  242. parse_list_header('token, "quoted value"')
  243. ['token', 'quoted value']
  244. This is the reverse of :func:`dump_header`.
  245. :param value: The header value to parse.
  246. .. versionchanged:: 3.2
  247. Quotes and escapes are kept if only part of an item is quoted. Empty
  248. values are omitted. An empty list is returned if the value contains an
  249. unclosed quoted string.
  250. """
  251. items = []
  252. item = ""
  253. escape = False
  254. quote = False
  255. for char in value:
  256. if escape:
  257. escape = False
  258. item += char
  259. continue
  260. if quote:
  261. if char == "\\":
  262. escape = True
  263. elif char == '"':
  264. quote = False
  265. item += char
  266. continue
  267. if char == ",":
  268. items.append(item)
  269. item = ""
  270. continue
  271. if char == '"':
  272. quote = True
  273. item += char
  274. if quote:
  275. # invalid, unclosed quoted string
  276. return []
  277. items.append(item)
  278. return [
  279. unquote_header_value(item) for item in (item.strip() for item in items) if item
  280. ]
  281. def parse_dict_header(value: str) -> dict[str, str | None]:
  282. """Parse a list header using :func:`parse_list_header`, then parse each item as a
  283. ``key=value`` pair.
  284. .. code-block:: python
  285. parse_dict_header('a=b, c="d, e", f')
  286. {"a": "b", "c": "d, e", "f": None}
  287. This is the reverse of :func:`dump_header`.
  288. If a key does not have a value, it is ``None``.
  289. This handles charsets for values as described in
  290. `RFC 2231 <https://www.rfc-editor.org/rfc/rfc2231#section-3>`__. Only ASCII, UTF-8,
  291. and ISO-8859-1 charsets are accepted, otherwise the value remains quoted.
  292. :param value: The header value to parse.
  293. .. versionchanged:: 3.2
  294. An empty dict is returned if the value contains an unclosed quoted
  295. string.
  296. .. versionchanged:: 3.0
  297. Passing bytes is not supported.
  298. .. versionchanged:: 3.0
  299. The ``cls`` argument is removed.
  300. .. versionchanged:: 2.3
  301. Added support for ``key*=charset''value`` encoded items.
  302. .. versionchanged:: 0.9
  303. The ``cls`` argument was added.
  304. """
  305. result: dict[str, str | None] = {}
  306. for item in parse_list_header(value):
  307. key, has_value, value = item.partition("=")
  308. key = key.strip()
  309. if not key:
  310. # =value is not valid
  311. continue
  312. if not has_value:
  313. result[key] = None
  314. continue
  315. value = value.strip()
  316. encoding: str | None = None
  317. if key[-1] == "*":
  318. # key*=charset''value becomes key=value, where value is percent encoded
  319. # adapted from parse_options_header, without the continuation handling
  320. key = key[:-1]
  321. match = _charset_value_re.match(value)
  322. if match:
  323. # If there is a charset marker in the value, split it off.
  324. encoding, value = match.groups()
  325. encoding = encoding.lower()
  326. # A safe list of encodings. Modern clients should only send ASCII or UTF-8.
  327. # This list will not be extended further. An invalid encoding will leave the
  328. # value quoted.
  329. if encoding in {"ascii", "us-ascii", "utf-8", "iso-8859-1"}:
  330. # invalid bytes are replaced during unquoting
  331. value = unquote(value, encoding=encoding)
  332. result[key] = unquote_header_value(value)
  333. return result
  334. # https://httpwg.org/specs/rfc9110.html#parameter
  335. _parameter_key_re = re.compile(r"([\w!#$%&'*+\-.^`|~]+)=", flags=re.ASCII)
  336. _parameter_token_value_re = re.compile(r"[\w!#$%&'*+\-.^`|~]+", flags=re.ASCII)
  337. # https://www.rfc-editor.org/rfc/rfc2231#section-4
  338. _charset_value_re = re.compile(
  339. r"""
  340. ([\w!#$%&*+\-.^`|~]*)' # charset part, could be empty
  341. [\w!#$%&*+\-.^`|~]*' # don't care about language part, usually empty
  342. ([\w!#$%&'*+\-.^`|~]+) # one or more token chars with percent encoding
  343. """,
  344. re.ASCII | re.VERBOSE,
  345. )
  346. # https://www.rfc-editor.org/rfc/rfc2231#section-3
  347. _continuation_re = re.compile(r"\*(\d+)$", re.ASCII)
  348. def parse_options_header(value: str | None) -> tuple[str, dict[str, str]]:
  349. """Parse a header that consists of a value with ``key=value`` parameters separated
  350. by semicolons ``;``. For example, the ``Content-Type`` header.
  351. .. code-block:: python
  352. parse_options_header("text/html; charset=UTF-8")
  353. ('text/html', {'charset': 'UTF-8'})
  354. parse_options_header("")
  355. ("", {})
  356. This is the reverse of :func:`dump_options_header`.
  357. This parses valid parameter parts as described in
  358. `RFC 9110 <https://httpwg.org/specs/rfc9110.html#parameter>`__. Invalid parts are
  359. skipped.
  360. This handles continuations and charsets as described in
  361. `RFC 2231 <https://www.rfc-editor.org/rfc/rfc2231#section-3>`__, although not as
  362. strictly as the RFC. Only ASCII, UTF-8, and ISO-8859-1 charsets are accepted,
  363. otherwise the value remains quoted.
  364. Clients may not be consistent in how they handle a quote character within a quoted
  365. value. The `HTML Standard <https://html.spec.whatwg.org/#multipart-form-data>`__
  366. replaces it with ``%22`` in multipart form data.
  367. `RFC 9110 <https://httpwg.org/specs/rfc9110.html#quoted.strings>`__ uses backslash
  368. escapes in HTTP headers. Both are decoded to the ``"`` character.
  369. Clients may not be consistent in how they handle non-ASCII characters. HTML
  370. documents must declare ``<meta charset=UTF-8>``, otherwise browsers may replace with
  371. HTML character references, which can be decoded using :func:`html.unescape`.
  372. :param value: The header value to parse.
  373. :return: ``(value, options)``, where ``options`` is a dict
  374. .. versionchanged:: 2.3
  375. Invalid parts, such as keys with no value, quoted keys, and incorrectly quoted
  376. values, are discarded instead of treating as ``None``.
  377. .. versionchanged:: 2.3
  378. Only ASCII, UTF-8, and ISO-8859-1 are accepted for charset values.
  379. .. versionchanged:: 2.3
  380. Escaped quotes in quoted values, like ``%22`` and ``\\"``, are handled.
  381. .. versionchanged:: 2.2
  382. Option names are always converted to lowercase.
  383. .. versionchanged:: 2.2
  384. The ``multiple`` parameter was removed.
  385. .. versionchanged:: 0.15
  386. :rfc:`2231` parameter continuations are handled.
  387. .. versionadded:: 0.5
  388. """
  389. if value is None:
  390. return "", {}
  391. value, _, rest = value.partition(";")
  392. value = value.strip()
  393. rest = rest.strip()
  394. if not value or not rest:
  395. # empty (invalid) value, or value without options
  396. return value, {}
  397. # Collect all valid key=value parts without processing the value.
  398. parts: list[tuple[str, str]] = []
  399. while True:
  400. if (m := _parameter_key_re.match(rest)) is not None:
  401. pk = m.group(1).lower()
  402. rest = rest[m.end() :]
  403. # Value may be a token.
  404. if (m := _parameter_token_value_re.match(rest)) is not None:
  405. parts.append((pk, m.group()))
  406. # Value may be a quoted string, find the closing quote.
  407. elif rest[:1] == '"':
  408. pos = 1
  409. length = len(rest)
  410. while pos < length:
  411. if rest[pos : pos + 2] in {"\\\\", '\\"'}:
  412. # Consume escaped slashes and quotes.
  413. pos += 2
  414. elif rest[pos] == '"':
  415. # Stop at an unescaped quote.
  416. parts.append((pk, rest[: pos + 1]))
  417. rest = rest[pos + 1 :]
  418. break
  419. else:
  420. # Consume any other character.
  421. pos += 1
  422. # Find the next section delimited by `;`, if any.
  423. if (end := rest.find(";")) == -1:
  424. break
  425. rest = rest[end + 1 :].lstrip()
  426. options: dict[str, str] = {}
  427. encoding: str | None = None
  428. continued_encoding: str | None = None
  429. # For each collected part, process optional charset and continuation,
  430. # unquote quoted values.
  431. for pk, pv in parts:
  432. if pk[-1] == "*":
  433. # key*=charset''value becomes key=value, where value is percent encoded
  434. pk = pk[:-1]
  435. match = _charset_value_re.match(pv)
  436. if match:
  437. # If there is a valid charset marker in the value, split it off.
  438. encoding, pv = match.groups()
  439. # This might be the empty string, handled next.
  440. encoding = encoding.lower()
  441. # No charset marker, or marker with empty charset value.
  442. if not encoding:
  443. encoding = continued_encoding
  444. # A safe list of encodings. Modern clients should only send ASCII or UTF-8.
  445. # This list will not be extended further. An invalid encoding will leave the
  446. # value quoted.
  447. if encoding in {"ascii", "us-ascii", "utf-8", "iso-8859-1"}:
  448. # Continuation parts don't require their own charset marker. This is
  449. # looser than the RFC, it will persist across different keys and allows
  450. # changing the charset during a continuation. But this implementation is
  451. # much simpler than tracking the full state.
  452. continued_encoding = encoding
  453. # invalid bytes are replaced during unquoting
  454. pv = unquote(pv, encoding=encoding)
  455. # Remove quotes. At this point the value cannot be empty or a single quote.
  456. if pv[0] == pv[-1] == '"':
  457. # HTTP headers use slash, multipart form data uses percent
  458. pv = pv[1:-1].replace("\\\\", "\\").replace('\\"', '"').replace("%22", '"')
  459. match = _continuation_re.search(pk)
  460. if match:
  461. # key*0=a; key*1=b becomes key=ab
  462. pk = pk[: match.start()]
  463. options[pk] = options.get(pk, "") + pv
  464. else:
  465. options[pk] = pv
  466. return value, options
  467. _q_value_re = re.compile(r"-?\d+(\.\d+)?", re.ASCII)
  468. _TAnyAccept = t.TypeVar("_TAnyAccept", bound="ds.Accept")
  469. @t.overload
  470. def parse_accept_header(value: str | None) -> ds.Accept: ...
  471. @t.overload
  472. def parse_accept_header(value: str | None, cls: type[_TAnyAccept]) -> _TAnyAccept: ...
  473. def parse_accept_header(
  474. value: str | None, cls: type[_TAnyAccept] | None = None
  475. ) -> _TAnyAccept:
  476. """Parse an ``Accept`` header according to
  477. `RFC 9110 <https://httpwg.org/specs/rfc9110.html#field.accept>`__.
  478. Returns an :class:`.Accept` instance, which can sort and inspect items based on
  479. their quality parameter. When parsing ``Accept-Charset``, ``Accept-Encoding``, or
  480. ``Accept-Language``, pass the appropriate :class:`.Accept` subclass.
  481. :param value: The header value to parse.
  482. :param cls: The :class:`.Accept` class to wrap the result in.
  483. :return: An instance of ``cls``.
  484. .. versionchanged:: 2.3
  485. Parse according to RFC 9110. Items with invalid ``q`` values are skipped.
  486. """
  487. if cls is None:
  488. cls = t.cast(type[_TAnyAccept], ds.Accept)
  489. if not value:
  490. return cls(None)
  491. result = []
  492. for item in parse_list_header(value):
  493. item, options = parse_options_header(item)
  494. if "q" in options:
  495. # pop q, remaining options are reconstructed
  496. q_str = options.pop("q").strip()
  497. if _q_value_re.fullmatch(q_str) is None:
  498. # ignore an invalid q
  499. continue
  500. q = float(q_str)
  501. if q < 0 or q > 1:
  502. # ignore an invalid q
  503. continue
  504. else:
  505. q = 1
  506. if options:
  507. # reconstruct the media type with any options
  508. item = dump_options_header(item, options)
  509. result.append((item, q))
  510. return cls(result)
  511. _TAnyCC = t.TypeVar("_TAnyCC", bound="ds.cache_control._CacheControl")
  512. @t.overload
  513. def parse_cache_control_header(
  514. value: str | None,
  515. on_update: t.Callable[[ds.cache_control._CacheControl], None] | None = None,
  516. ) -> ds.RequestCacheControl: ...
  517. @t.overload
  518. def parse_cache_control_header(
  519. value: str | None,
  520. on_update: t.Callable[[ds.cache_control._CacheControl], None] | None = None,
  521. cls: type[_TAnyCC] = ...,
  522. ) -> _TAnyCC: ...
  523. def parse_cache_control_header(
  524. value: str | None,
  525. on_update: t.Callable[[ds.cache_control._CacheControl], None] | None = None,
  526. cls: type[_TAnyCC] | None = None,
  527. ) -> _TAnyCC:
  528. """Parse a cache control header. The RFC differs between response and
  529. request cache control, this method does not. It's your responsibility
  530. to not use the wrong control statements.
  531. .. versionadded:: 0.5
  532. The `cls` was added. If not specified an immutable
  533. :class:`~werkzeug.datastructures.RequestCacheControl` is returned.
  534. :param value: a cache control header to be parsed.
  535. :param on_update: an optional callable that is called every time a value
  536. on the :class:`~werkzeug.datastructures.CacheControl`
  537. object is changed.
  538. :param cls: the class for the returned object. By default
  539. :class:`~werkzeug.datastructures.RequestCacheControl` is used.
  540. :return: a `cls` object.
  541. """
  542. if cls is None:
  543. cls = t.cast("type[_TAnyCC]", ds.RequestCacheControl)
  544. if not value:
  545. return cls((), on_update)
  546. return cls(parse_dict_header(value), on_update)
  547. _TAnyCSP = t.TypeVar("_TAnyCSP", bound="ds.ContentSecurityPolicy")
  548. @t.overload
  549. def parse_csp_header(
  550. value: str | None,
  551. on_update: t.Callable[[ds.ContentSecurityPolicy], None] | None = None,
  552. ) -> ds.ContentSecurityPolicy: ...
  553. @t.overload
  554. def parse_csp_header(
  555. value: str | None,
  556. on_update: t.Callable[[ds.ContentSecurityPolicy], None] | None = None,
  557. cls: type[_TAnyCSP] = ...,
  558. ) -> _TAnyCSP: ...
  559. def parse_csp_header(
  560. value: str | None,
  561. on_update: t.Callable[[ds.ContentSecurityPolicy], None] | None = None,
  562. cls: type[_TAnyCSP] | None = None,
  563. ) -> _TAnyCSP:
  564. """Parse a Content Security Policy header.
  565. .. versionadded:: 1.0.0
  566. Support for Content Security Policy headers was added.
  567. :param value: a csp header to be parsed.
  568. :param on_update: an optional callable that is called every time a value
  569. on the object is changed.
  570. :param cls: the class for the returned object. By default
  571. :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used.
  572. :return: a `cls` object.
  573. """
  574. if cls is None:
  575. cls = t.cast("type[_TAnyCSP]", ds.ContentSecurityPolicy)
  576. if value is None:
  577. return cls((), on_update)
  578. items = []
  579. for policy in value.split(";"):
  580. policy = policy.strip()
  581. # Ignore badly formatted policies (no space)
  582. if " " in policy:
  583. directive, value = policy.strip().split(" ", 1)
  584. items.append((directive.strip(), value.strip()))
  585. return cls(items, on_update)
  586. def parse_set_header(
  587. value: str | None,
  588. on_update: t.Callable[[ds.HeaderSet], None] | None = None,
  589. ) -> ds.HeaderSet:
  590. """Parse a set-like header and return a
  591. :class:`~werkzeug.datastructures.HeaderSet` object:
  592. >>> hs = parse_set_header('token, "quoted value"')
  593. The return value is an object that treats the items case-insensitively
  594. and keeps the order of the items:
  595. >>> 'TOKEN' in hs
  596. True
  597. >>> hs.index('quoted value')
  598. 1
  599. >>> hs
  600. HeaderSet(['token', 'quoted value'])
  601. To create a header from the :class:`HeaderSet` again, use the
  602. :func:`dump_header` function.
  603. :param value: a set header to be parsed.
  604. :param on_update: an optional callable that is called every time a
  605. value on the :class:`~werkzeug.datastructures.HeaderSet`
  606. object is changed.
  607. :return: a :class:`~werkzeug.datastructures.HeaderSet`
  608. """
  609. if not value:
  610. return ds.HeaderSet(None, on_update)
  611. return ds.HeaderSet(parse_list_header(value), on_update)
  612. def parse_if_range_header(value: str | None) -> ds.IfRange:
  613. """Parses an if-range header which can be an etag or a date. Returns
  614. a :class:`~werkzeug.datastructures.IfRange` object.
  615. .. versionchanged:: 2.0
  616. If the value represents a datetime, it is timezone-aware.
  617. .. versionadded:: 0.7
  618. """
  619. if not value:
  620. return ds.IfRange()
  621. date = parse_date(value)
  622. if date is not None:
  623. return ds.IfRange(date=date)
  624. # drop weakness information
  625. return ds.IfRange(unquote_etag(value)[0])
  626. def parse_range_header(
  627. value: str | None, make_inclusive: bool = True
  628. ) -> ds.Range | None:
  629. """Parses a range header into a :class:`~werkzeug.datastructures.Range`
  630. object. If the header is missing or malformed `None` is returned.
  631. `ranges` is a list of ``(start, stop)`` tuples where the ranges are
  632. non-inclusive.
  633. .. versionadded:: 0.7
  634. """
  635. if not value or "=" not in value:
  636. return None
  637. ranges = []
  638. last_end = 0
  639. units, rng = value.split("=", 1)
  640. units = units.strip().lower()
  641. for item in rng.split(","):
  642. item = item.strip()
  643. if "-" not in item:
  644. return None
  645. if item.startswith("-"):
  646. if last_end < 0:
  647. return None
  648. try:
  649. begin = _plain_int(item)
  650. except ValueError:
  651. return None
  652. end = None
  653. last_end = -1
  654. elif "-" in item:
  655. begin_str, end_str = item.split("-", 1)
  656. begin_str = begin_str.strip()
  657. end_str = end_str.strip()
  658. try:
  659. begin = _plain_int(begin_str)
  660. except ValueError:
  661. return None
  662. if begin < last_end or last_end < 0:
  663. return None
  664. if end_str:
  665. try:
  666. end = _plain_int(end_str) + 1
  667. except ValueError:
  668. return None
  669. if begin >= end:
  670. return None
  671. else:
  672. end = None
  673. last_end = end if end is not None else -1
  674. ranges.append((begin, end))
  675. return ds.Range(units, ranges)
  676. def parse_content_range_header(
  677. value: str | None,
  678. on_update: t.Callable[[ds.ContentRange], None] | None = None,
  679. ) -> ds.ContentRange | None:
  680. """Parses a range header into a
  681. :class:`~werkzeug.datastructures.ContentRange` object or `None` if
  682. parsing is not possible.
  683. .. versionadded:: 0.7
  684. :param value: a content range header to be parsed.
  685. :param on_update: an optional callable that is called every time a value
  686. on the :class:`~werkzeug.datastructures.ContentRange`
  687. object is changed.
  688. """
  689. if value is None:
  690. return None
  691. try:
  692. units, rangedef = (value or "").strip().split(None, 1)
  693. except ValueError:
  694. return None
  695. if "/" not in rangedef:
  696. return None
  697. rng, length_str = rangedef.split("/", 1)
  698. if length_str == "*":
  699. length = None
  700. else:
  701. try:
  702. length = _plain_int(length_str)
  703. except ValueError:
  704. return None
  705. if rng == "*":
  706. if not is_byte_range_valid(None, None, length):
  707. return None
  708. return ds.ContentRange(units, None, None, length, on_update=on_update)
  709. elif "-" not in rng:
  710. return None
  711. start_str, stop_str = rng.split("-", 1)
  712. try:
  713. start = _plain_int(start_str)
  714. stop = _plain_int(stop_str) + 1
  715. except ValueError:
  716. return None
  717. if is_byte_range_valid(start, stop, length):
  718. return ds.ContentRange(units, start, stop, length, on_update=on_update)
  719. return None
  720. def quote_etag(etag: str, weak: bool = False) -> str:
  721. """Quote an etag.
  722. :param etag: the etag to quote.
  723. :param weak: set to `True` to tag it "weak".
  724. """
  725. if '"' in etag:
  726. raise ValueError("invalid etag")
  727. etag = f'"{etag}"'
  728. if weak:
  729. etag = f"W/{etag}"
  730. return etag
  731. @t.overload
  732. def unquote_etag(etag: str) -> tuple[str, bool]: ...
  733. @t.overload
  734. def unquote_etag(etag: None) -> tuple[None, None]: ...
  735. def unquote_etag(
  736. etag: str | None,
  737. ) -> tuple[str, bool] | tuple[None, None]:
  738. """Unquote a single etag:
  739. >>> unquote_etag('W/"bar"')
  740. ('bar', True)
  741. >>> unquote_etag('"bar"')
  742. ('bar', False)
  743. :param etag: the etag identifier to unquote.
  744. :return: a ``(etag, weak)`` tuple.
  745. """
  746. if not etag:
  747. return None, None
  748. etag = etag.strip()
  749. weak = False
  750. if etag.startswith(("W/", "w/")):
  751. weak = True
  752. etag = etag[2:]
  753. if etag[:1] == etag[-1:] == '"':
  754. etag = etag[1:-1]
  755. return etag, weak
  756. def parse_etags(value: str | None) -> ds.ETags:
  757. """Parse an etag header.
  758. :param value: the tag header to parse
  759. :return: an :class:`~werkzeug.datastructures.ETags` object.
  760. """
  761. if not value:
  762. return ds.ETags()
  763. strong = []
  764. weak = []
  765. end = len(value)
  766. pos = 0
  767. while pos < end:
  768. match = _etag_re.match(value, pos)
  769. if match is None:
  770. break
  771. is_weak, quoted, raw = match.groups()
  772. if raw == "*":
  773. return ds.ETags(star_tag=True)
  774. elif quoted:
  775. raw = quoted
  776. if is_weak:
  777. weak.append(raw)
  778. else:
  779. strong.append(raw)
  780. pos = match.end()
  781. return ds.ETags(strong, weak)
  782. def generate_etag(data: bytes) -> str:
  783. """Generate an etag for some data.
  784. .. versionchanged:: 2.0
  785. Use SHA-1. MD5 may not be available in some environments.
  786. """
  787. return sha1(data).hexdigest()
  788. def parse_date(value: str | None) -> datetime | None:
  789. """Parse an :rfc:`2822` date into a timezone-aware
  790. :class:`datetime.datetime` object, or ``None`` if parsing fails.
  791. This is a wrapper for :func:`email.utils.parsedate_to_datetime`. It
  792. returns ``None`` if parsing fails instead of raising an exception,
  793. and always returns a timezone-aware datetime object. If the string
  794. doesn't have timezone information, it is assumed to be UTC.
  795. :param value: A string with a supported date format.
  796. .. versionchanged:: 2.0
  797. Return a timezone-aware datetime object. Use
  798. ``email.utils.parsedate_to_datetime``.
  799. """
  800. if value is None:
  801. return None
  802. try:
  803. dt = email.utils.parsedate_to_datetime(value)
  804. except (TypeError, ValueError):
  805. return None
  806. if dt.tzinfo is None:
  807. return dt.replace(tzinfo=timezone.utc)
  808. return dt
  809. def http_date(
  810. timestamp: datetime | date | int | float | struct_time | None = None,
  811. ) -> str:
  812. """Format a datetime object or timestamp into an :rfc:`2822` date
  813. string.
  814. This is a wrapper for :func:`email.utils.format_datetime`. It
  815. assumes naive datetime objects are in UTC instead of raising an
  816. exception.
  817. :param timestamp: The datetime or timestamp to format. Defaults to
  818. the current time.
  819. .. versionchanged:: 2.0
  820. Use ``email.utils.format_datetime``. Accept ``date`` objects.
  821. """
  822. if isinstance(timestamp, date):
  823. if not isinstance(timestamp, datetime):
  824. # Assume plain date is midnight UTC.
  825. timestamp = datetime.combine(timestamp, time(), tzinfo=timezone.utc)
  826. else:
  827. # Ensure datetime is timezone-aware.
  828. timestamp = _dt_as_utc(timestamp)
  829. return email.utils.format_datetime(timestamp, usegmt=True)
  830. if isinstance(timestamp, struct_time):
  831. timestamp = mktime(timestamp)
  832. return email.utils.formatdate(timestamp, usegmt=True)
  833. def parse_age(value: str | None = None) -> timedelta | None:
  834. """Parses a base-10 integer count of seconds into a timedelta.
  835. If parsing fails, the return value is `None`.
  836. :param value: a string consisting of an integer represented in base-10
  837. :return: a :class:`datetime.timedelta` object or `None`.
  838. """
  839. if not value:
  840. return None
  841. try:
  842. seconds = int(value)
  843. except ValueError:
  844. return None
  845. if seconds < 0:
  846. return None
  847. try:
  848. return timedelta(seconds=seconds)
  849. except OverflowError:
  850. return None
  851. def dump_age(age: timedelta | int | None = None) -> str | None:
  852. """Formats the duration as a base-10 integer.
  853. :param age: should be an integer number of seconds,
  854. a :class:`datetime.timedelta` object, or,
  855. if the age is unknown, `None` (default).
  856. """
  857. if age is None:
  858. return None
  859. if isinstance(age, timedelta):
  860. age = int(age.total_seconds())
  861. else:
  862. age = int(age)
  863. if age < 0:
  864. raise ValueError("age cannot be negative")
  865. return str(age)
  866. def is_resource_modified(
  867. environ: WSGIEnvironment,
  868. etag: str | None = None,
  869. data: bytes | None = None,
  870. last_modified: datetime | str | None = None,
  871. ignore_if_range: bool = True,
  872. ) -> bool:
  873. """Convenience method for conditional requests.
  874. :param environ: the WSGI environment of the request to be checked.
  875. :param etag: the etag for the response for comparison.
  876. :param data: or alternatively the data of the response to automatically
  877. generate an etag using :func:`generate_etag`.
  878. :param last_modified: an optional date of the last modification.
  879. :param ignore_if_range: If `False`, `If-Range` header will be taken into
  880. account.
  881. :return: `True` if the resource was modified, otherwise `False`.
  882. .. versionchanged:: 2.0
  883. SHA-1 is used to generate an etag value for the data. MD5 may
  884. not be available in some environments.
  885. .. versionchanged:: 1.0.0
  886. The check is run for methods other than ``GET`` and ``HEAD``.
  887. """
  888. return _sansio_http.is_resource_modified(
  889. http_range=environ.get("HTTP_RANGE"),
  890. http_if_range=environ.get("HTTP_IF_RANGE"),
  891. http_if_modified_since=environ.get("HTTP_IF_MODIFIED_SINCE"),
  892. http_if_none_match=environ.get("HTTP_IF_NONE_MATCH"),
  893. http_if_match=environ.get("HTTP_IF_MATCH"),
  894. etag=etag,
  895. data=data,
  896. last_modified=last_modified,
  897. ignore_if_range=ignore_if_range,
  898. )
  899. def remove_entity_headers(
  900. headers: ds.Headers | list[tuple[str, str]],
  901. allowed: t.Iterable[str] = ("expires", "content-location"),
  902. ) -> None:
  903. """Remove all entity headers from a list or :class:`Headers` object. This
  904. operation works in-place. `Expires` and `Content-Location` headers are
  905. by default not removed. The reason for this is :rfc:`2616` section
  906. 10.3.5 which specifies some entity headers that should be sent.
  907. .. versionchanged:: 0.5
  908. added `allowed` parameter.
  909. :param headers: a list or :class:`Headers` object.
  910. :param allowed: a list of headers that should still be allowed even though
  911. they are entity headers.
  912. """
  913. allowed = {x.lower() for x in allowed}
  914. headers[:] = [
  915. (key, value)
  916. for key, value in headers
  917. if not is_entity_header(key) or key.lower() in allowed
  918. ]
  919. def remove_hop_by_hop_headers(headers: ds.Headers | list[tuple[str, str]]) -> None:
  920. """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or
  921. :class:`Headers` object. This operation works in-place.
  922. .. versionadded:: 0.5
  923. :param headers: a list or :class:`Headers` object.
  924. """
  925. headers[:] = [
  926. (key, value) for key, value in headers if not is_hop_by_hop_header(key)
  927. ]
  928. def is_entity_header(header: str) -> bool:
  929. """Check if a header is an entity header.
  930. .. versionadded:: 0.5
  931. :param header: the header to test.
  932. :return: `True` if it's an entity header, `False` otherwise.
  933. """
  934. return header.lower() in _entity_headers
  935. def is_hop_by_hop_header(header: str) -> bool:
  936. """Check if a header is an HTTP/1.1 "Hop-by-Hop" header.
  937. .. versionadded:: 0.5
  938. :param header: the header to test.
  939. :return: `True` if it's an HTTP/1.1 "Hop-by-Hop" header, `False` otherwise.
  940. """
  941. return header.lower() in _hop_by_hop_headers
  942. def parse_cookie(
  943. header: WSGIEnvironment | str | None,
  944. cls: type[ds.MultiDict[str, str]] | None = None,
  945. ) -> ds.MultiDict[str, str]:
  946. """Parse a cookie from a string or WSGI environ.
  947. The same key can be provided multiple times, the values are stored
  948. in-order. The default :class:`MultiDict` will have the first value
  949. first, and all values can be retrieved with
  950. :meth:`MultiDict.getlist`.
  951. :param header: The cookie header as a string, or a WSGI environ dict
  952. with a ``HTTP_COOKIE`` key.
  953. :param cls: A dict-like class to store the parsed cookies in.
  954. Defaults to :class:`MultiDict`.
  955. .. versionchanged:: 3.0
  956. Passing bytes, and the ``charset`` and ``errors`` parameters, were removed.
  957. .. versionchanged:: 1.0
  958. Returns a :class:`MultiDict` instead of a ``TypeConversionDict``.
  959. .. versionchanged:: 0.5
  960. Returns a :class:`TypeConversionDict` instead of a regular dict. The ``cls``
  961. parameter was added.
  962. """
  963. if isinstance(header, dict):
  964. cookie = header.get("HTTP_COOKIE")
  965. else:
  966. cookie = header
  967. if cookie:
  968. cookie = cookie.encode("latin1").decode()
  969. return _sansio_http.parse_cookie(cookie=cookie, cls=cls)
  970. _cookie_no_quote_re = re.compile(r"[\w!#$%&'()*+\-./:<=>?@\[\]^`{|}~]*", re.A)
  971. _cookie_slash_re = re.compile(rb"[\x00-\x19\",;\\\x7f-\xff]", re.A)
  972. _cookie_slash_map = {b'"': b'\\"', b"\\": b"\\\\"}
  973. _cookie_slash_map.update(
  974. (v.to_bytes(1, "big"), b"\\%03o" % v)
  975. for v in [*range(0x20), *b",;", *range(0x7F, 256)]
  976. )
  977. def dump_cookie(
  978. key: str,
  979. value: str = "",
  980. max_age: timedelta | int | None = None,
  981. expires: str | datetime | int | float | None = None,
  982. path: str | None = "/",
  983. domain: str | None = None,
  984. secure: bool = False,
  985. httponly: bool = False,
  986. sync_expires: bool = True,
  987. max_size: int = 4093,
  988. samesite: str | None = None,
  989. partitioned: bool = False,
  990. ) -> str:
  991. """Create a Set-Cookie header without the ``Set-Cookie`` prefix.
  992. The return value is usually restricted to ascii as the vast majority
  993. of values are properly escaped, but that is no guarantee. It's
  994. tunneled through latin1 as required by :pep:`3333`.
  995. The return value is not ASCII safe if the key contains unicode
  996. characters. This is technically against the specification but
  997. happens in the wild. It's strongly recommended to not use
  998. non-ASCII values for the keys.
  999. :param max_age: should be a number of seconds, or `None` (default) if
  1000. the cookie should last only as long as the client's
  1001. browser session. Additionally `timedelta` objects
  1002. are accepted, too.
  1003. :param expires: should be a `datetime` object or unix timestamp.
  1004. :param path: limits the cookie to a given path, per default it will
  1005. span the whole domain.
  1006. :param domain: Use this if you want to set a cross-domain cookie. For
  1007. example, ``domain="example.com"`` will set a cookie
  1008. that is readable by the domain ``www.example.com``,
  1009. ``foo.example.com`` etc. Otherwise, a cookie will only
  1010. be readable by the domain that set it.
  1011. :param secure: The cookie will only be available via HTTPS
  1012. :param httponly: disallow JavaScript to access the cookie. This is an
  1013. extension to the cookie standard and probably not
  1014. supported by all browsers.
  1015. :param charset: the encoding for string values.
  1016. :param sync_expires: automatically set expires if max_age is defined
  1017. but expires not.
  1018. :param max_size: Warn if the final header value exceeds this size. The
  1019. default, 4093, should be safely `supported by most browsers
  1020. <cookie_>`_. Set to 0 to disable this check.
  1021. :param samesite: Limits the scope of the cookie such that it will
  1022. only be attached to requests if those requests are same-site.
  1023. :param partitioned: Opts the cookie into partitioned storage. This
  1024. will also set secure to True
  1025. .. _`cookie`: http://browsercookielimits.squawky.net/
  1026. .. versionchanged:: 3.1
  1027. The ``partitioned`` parameter was added.
  1028. .. versionchanged:: 3.0
  1029. Passing bytes, and the ``charset`` parameter, were removed.
  1030. .. versionchanged:: 2.3.3
  1031. The ``path`` parameter is ``/`` by default.
  1032. .. versionchanged:: 2.3.1
  1033. The value allows more characters without quoting.
  1034. .. versionchanged:: 2.3
  1035. ``localhost`` and other names without a dot are allowed for the domain. A
  1036. leading dot is ignored.
  1037. .. versionchanged:: 2.3
  1038. The ``path`` parameter is ``None`` by default.
  1039. .. versionchanged:: 1.0.0
  1040. The string ``'None'`` is accepted for ``samesite``.
  1041. """
  1042. if path is not None:
  1043. # safe = https://url.spec.whatwg.org/#url-path-segment-string
  1044. # as well as percent for things that are already quoted
  1045. # excluding semicolon since it's part of the header syntax
  1046. path = quote(path, safe="%!$&'()*+,/:=@")
  1047. if domain:
  1048. domain = domain.partition(":")[0].lstrip(".").encode("idna").decode("ascii")
  1049. if isinstance(max_age, timedelta):
  1050. max_age = int(max_age.total_seconds())
  1051. if expires is not None:
  1052. if not isinstance(expires, str):
  1053. expires = http_date(expires)
  1054. elif max_age is not None and sync_expires:
  1055. expires = http_date(datetime.now(tz=timezone.utc).timestamp() + max_age)
  1056. if samesite is not None:
  1057. samesite = samesite.title()
  1058. if samesite not in {"Strict", "Lax", "None"}:
  1059. raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.")
  1060. if partitioned:
  1061. secure = True
  1062. # Quote value if it contains characters not allowed by RFC 6265. Slash-escape with
  1063. # three octal digits, which matches http.cookies, although the RFC suggests base64.
  1064. if not _cookie_no_quote_re.fullmatch(value):
  1065. # Work with bytes here, since a UTF-8 character could be multiple bytes.
  1066. value = _cookie_slash_re.sub(
  1067. lambda m: _cookie_slash_map[m.group()], value.encode()
  1068. ).decode("ascii")
  1069. value = f'"{value}"'
  1070. # Send a non-ASCII key as mojibake. Everything else should already be ASCII.
  1071. # TODO Remove encoding dance, it seems like clients accept UTF-8 keys
  1072. buf = [f"{key.encode().decode('latin1')}={value}"]
  1073. for k, v in (
  1074. ("Domain", domain),
  1075. ("Expires", expires),
  1076. ("Max-Age", max_age),
  1077. ("Secure", secure),
  1078. ("HttpOnly", httponly),
  1079. ("Path", path),
  1080. ("SameSite", samesite),
  1081. ("Partitioned", partitioned),
  1082. ):
  1083. if v is None or v is False:
  1084. continue
  1085. if v is True:
  1086. buf.append(k)
  1087. continue
  1088. buf.append(f"{k}={v}")
  1089. rv = "; ".join(buf)
  1090. # Warn if the final value of the cookie is larger than the limit. If the cookie is
  1091. # too large, then it may be silently ignored by the browser, which can be quite hard
  1092. # to debug.
  1093. cookie_size = len(rv)
  1094. if max_size and cookie_size > max_size:
  1095. value_size = len(value)
  1096. warnings.warn(
  1097. f"The '{key}' cookie is too large: the value was {value_size} bytes but the"
  1098. f" header required {cookie_size - value_size} extra bytes. The final size"
  1099. f" was {cookie_size} bytes but the limit is {max_size} bytes. Browsers may"
  1100. " silently ignore cookies larger than this.",
  1101. stacklevel=2,
  1102. )
  1103. return rv
  1104. def is_byte_range_valid(
  1105. start: int | None, stop: int | None, length: int | None
  1106. ) -> bool:
  1107. """Checks if a given byte content range is valid for the given length.
  1108. .. versionadded:: 0.7
  1109. """
  1110. if (start is None) != (stop is None):
  1111. return False
  1112. elif start is None:
  1113. return length is None or length >= 0
  1114. elif length is None:
  1115. return 0 <= start < stop # type: ignore
  1116. elif start >= stop: # type: ignore
  1117. return False
  1118. return 0 <= start < length
  1119. # circular dependencies
  1120. from . import datastructures as ds # noqa: E402
  1121. from .sansio import http as _sansio_http # noqa: E402