http.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. from __future__ import annotations
  2. import re
  3. import typing as t
  4. from datetime import datetime
  5. from .._internal import _dt_as_utc
  6. from ..http import generate_etag
  7. from ..http import parse_date
  8. from ..http import parse_etags
  9. from ..http import parse_if_range_header
  10. from ..http import unquote_etag
  11. def is_resource_modified(
  12. http_range: str | None = None,
  13. http_if_range: str | None = None,
  14. http_if_modified_since: str | None = None,
  15. http_if_none_match: str | None = None,
  16. http_if_match: str | None = None,
  17. etag: str | None = None,
  18. data: bytes | None = None,
  19. last_modified: datetime | str | None = None,
  20. ignore_if_range: bool = True,
  21. ) -> bool:
  22. """Convenience method for conditional requests.
  23. :param http_range: Range HTTP header
  24. :param http_if_range: If-Range HTTP header
  25. :param http_if_modified_since: If-Modified-Since HTTP header
  26. :param http_if_none_match: If-None-Match HTTP header
  27. :param http_if_match: If-Match HTTP header
  28. :param etag: the etag for the response for comparison.
  29. :param data: or alternatively the data of the response to automatically
  30. generate an etag using :func:`generate_etag`.
  31. :param last_modified: an optional date of the last modification.
  32. :param ignore_if_range: If `False`, `If-Range` header will be taken into
  33. account.
  34. :return: `True` if the resource was modified, otherwise `False`.
  35. .. versionadded:: 2.2
  36. """
  37. if etag is None and data is not None:
  38. etag = f'"{generate_etag(data)}"'
  39. elif data is not None:
  40. raise TypeError("both data and etag given")
  41. unmodified = False
  42. if isinstance(last_modified, str):
  43. last_modified = parse_date(last_modified)
  44. # HTTP doesn't use microsecond, remove it to avoid false positive
  45. # comparisons. Mark naive datetimes as UTC.
  46. if last_modified is not None:
  47. last_modified = _dt_as_utc(last_modified.replace(microsecond=0))
  48. if_range = None
  49. if not ignore_if_range and http_range is not None:
  50. # https://tools.ietf.org/html/rfc7233#section-3.2
  51. # A server MUST ignore an If-Range header field received in a request
  52. # that does not contain a Range header field.
  53. if_range = parse_if_range_header(http_if_range)
  54. if if_range is not None and if_range.date is not None:
  55. modified_since: datetime | None = if_range.date
  56. else:
  57. modified_since = parse_date(http_if_modified_since)
  58. if modified_since and last_modified and last_modified <= modified_since:
  59. unmodified = True
  60. if etag:
  61. etag, _ = unquote_etag(etag)
  62. if if_range is not None and if_range.etag is not None:
  63. unmodified = if_range.etag == etag
  64. else:
  65. if_none_match = parse_etags(http_if_none_match)
  66. if if_none_match:
  67. # https://tools.ietf.org/html/rfc7232#section-3.2
  68. # "A recipient MUST use the weak comparison function when comparing
  69. # entity-tags for If-None-Match"
  70. unmodified = if_none_match.contains_weak(etag)
  71. # https://tools.ietf.org/html/rfc7232#section-3.1
  72. # "Origin server MUST use the strong comparison function when
  73. # comparing entity-tags for If-Match"
  74. if_match = parse_etags(http_if_match)
  75. if if_match:
  76. unmodified = not if_match.is_strong(etag)
  77. return not unmodified
  78. _cookie_re = re.compile(
  79. r"""
  80. [ \t]* # ignore leading space
  81. ([^ \t=";]+) # key
  82. (?:[ \t]*=[ \t]* # optional =value, ignoring invalid space
  83. (
  84. "(?:[^\\"]|\\.)*" # quoted value with backslash escapes
  85. |
  86. [^ \t";]* # token value
  87. )
  88. )?
  89. [ \t]* # ignore trailing space
  90. (?:;|\Z) # only if followed by semicolon or end
  91. """,
  92. flags=re.ASCII | re.VERBOSE,
  93. )
  94. _cookie_unslash_re = re.compile(rb"\\([0-3][0-7]{2}|.)")
  95. def _cookie_unslash_replace(m: t.Match[bytes]) -> bytes:
  96. v = m.group(1)
  97. if len(v) == 1:
  98. return v
  99. return int(v, 8).to_bytes(1, "big")
  100. def parse_cookie(
  101. cookie: str | None = None,
  102. cls: type[ds.MultiDict[str, str]] | None = None,
  103. ) -> ds.MultiDict[str, str]:
  104. """Parse a cookie from a string.
  105. The same key can be provided multiple times, the values are stored
  106. in-order. The default :class:`MultiDict` will have the first value
  107. first, and all values can be retrieved with
  108. :meth:`MultiDict.getlist`.
  109. :param cookie: The cookie header as a string.
  110. :param cls: A dict-like class to store the parsed cookies in.
  111. Defaults to :class:`MultiDict`.
  112. .. versionchanged:: 3.0
  113. Passing bytes, and the ``charset`` and ``errors`` parameters, were removed.
  114. .. versionadded:: 2.2
  115. """
  116. if cls is None:
  117. cls = t.cast("type[ds.MultiDict[str, str]]", ds.MultiDict)
  118. if not cookie:
  119. return cls()
  120. out = []
  121. pos = 0
  122. while True:
  123. if (m := _cookie_re.match(cookie, pos)) is None:
  124. # Skip invalid chars until the next semicolon.
  125. if (pos := cookie.find(";", pos) + 1) == 0:
  126. break
  127. continue
  128. ck, cv = m.groups()
  129. pos = m.end()
  130. if cv is None:
  131. cv = ""
  132. if cv.startswith('"') and cv.endswith('"'):
  133. # Work with bytes here, since a UTF-8 character could be multiple bytes.
  134. cv = _cookie_unslash_re.sub(
  135. _cookie_unslash_replace, cv[1:-1].encode()
  136. ).decode(errors="replace")
  137. out.append((ck, cv))
  138. return cls(out)
  139. # circular dependencies
  140. from .. import datastructures as ds # noqa: E402