request.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. from __future__ import annotations
  2. import typing as t
  3. from datetime import datetime
  4. from urllib.parse import parse_qsl
  5. from ..datastructures import Accept
  6. from ..datastructures import Authorization
  7. from ..datastructures import CharsetAccept
  8. from ..datastructures import ETags
  9. from ..datastructures import Headers
  10. from ..datastructures import HeaderSet
  11. from ..datastructures import IfRange
  12. from ..datastructures import ImmutableList
  13. from ..datastructures import ImmutableMultiDict
  14. from ..datastructures import LanguageAccept
  15. from ..datastructures import MIMEAccept
  16. from ..datastructures import MultiDict
  17. from ..datastructures import Range
  18. from ..datastructures import RequestCacheControl
  19. from ..http import parse_accept_header
  20. from ..http import parse_cache_control_header
  21. from ..http import parse_date
  22. from ..http import parse_etags
  23. from ..http import parse_if_range_header
  24. from ..http import parse_list_header
  25. from ..http import parse_options_header
  26. from ..http import parse_range_header
  27. from ..http import parse_set_header
  28. from ..user_agent import UserAgent
  29. from ..utils import cached_property
  30. from ..utils import header_property
  31. from .http import parse_cookie
  32. from .utils import get_content_length
  33. from .utils import get_current_url
  34. from .utils import get_host
  35. class Request:
  36. """Represents the non-IO parts of a HTTP request, including the
  37. method, URL info, and headers.
  38. This class is not meant for general use. It should only be used when
  39. implementing WSGI, ASGI, or another HTTP application spec. Werkzeug
  40. provides a WSGI implementation at :cls:`werkzeug.wrappers.Request`.
  41. :param method: The method the request was made with, such as
  42. ``GET``.
  43. :param scheme: The URL scheme of the protocol the request used, such
  44. as ``https`` or ``wss``.
  45. :param server: The address of the server. ``(host, port)``,
  46. ``(path, None)`` for unix sockets, or ``None`` if not known.
  47. :param root_path: The prefix that the application is mounted under.
  48. This is prepended to generated URLs, but is not part of route
  49. matching.
  50. :param path: The path part of the URL after ``root_path``.
  51. :param query_string: The part of the URL after the "?".
  52. :param headers: The headers received with the request.
  53. :param remote_addr: The address of the client sending the request.
  54. .. versionchanged:: 3.0
  55. The ``charset``, ``url_charset``, and ``encoding_errors`` attributes
  56. were removed.
  57. .. versionadded:: 2.0
  58. """
  59. #: the class to use for `args` and `form`. The default is an
  60. #: :class:`~werkzeug.datastructures.ImmutableMultiDict` which supports
  61. #: multiple values per key. A :class:`~werkzeug.datastructures.ImmutableDict`
  62. #: is faster but only remembers the last key. It is also
  63. #: possible to use mutable structures, but this is not recommended.
  64. #:
  65. #: .. versionadded:: 0.6
  66. parameter_storage_class: type[MultiDict[str, t.Any]] = ImmutableMultiDict
  67. #: The type to be used for dict values from the incoming WSGI
  68. #: environment. (For example for :attr:`cookies`.) By default an
  69. #: :class:`~werkzeug.datastructures.ImmutableMultiDict` is used.
  70. #:
  71. #: .. versionchanged:: 1.0.0
  72. #: Changed to ``ImmutableMultiDict`` to support multiple values.
  73. #:
  74. #: .. versionadded:: 0.6
  75. dict_storage_class: type[MultiDict[str, t.Any]] = ImmutableMultiDict
  76. #: the type to be used for list values from the incoming WSGI environment.
  77. #: By default an :class:`~werkzeug.datastructures.ImmutableList` is used
  78. #: (for example for :attr:`access_list`).
  79. #:
  80. #: .. versionadded:: 0.6
  81. list_storage_class: type[list[t.Any]] = ImmutableList
  82. user_agent_class: type[UserAgent] = UserAgent
  83. """The class used and returned by the :attr:`user_agent` property to
  84. parse the header. Defaults to
  85. :class:`~werkzeug.user_agent.UserAgent`, which does no parsing. An
  86. extension can provide a subclass that uses a parser to provide other
  87. data.
  88. .. versionadded:: 2.0
  89. """
  90. #: Valid host names when handling requests. By default all hosts are
  91. #: trusted, which means that whatever the client says the host is
  92. #: will be accepted.
  93. #:
  94. #: Because ``Host`` and ``X-Forwarded-Host`` headers can be set to
  95. #: any value by a malicious client, it is recommended to either set
  96. #: this property or implement similar validation in the proxy (if
  97. #: the application is being run behind one).
  98. #:
  99. #: .. versionadded:: 0.9
  100. trusted_hosts: list[str] | None = None
  101. def __init__(
  102. self,
  103. method: str,
  104. scheme: str,
  105. server: tuple[str, int | None] | None,
  106. root_path: str,
  107. path: str,
  108. query_string: bytes,
  109. headers: Headers,
  110. remote_addr: str | None,
  111. ) -> None:
  112. #: The method the request was made with, such as ``GET``.
  113. self.method = method.upper()
  114. #: The URL scheme of the protocol the request used, such as
  115. #: ``https`` or ``wss``.
  116. self.scheme = scheme
  117. #: The address of the server. ``(host, port)``, ``(path, None)``
  118. #: for unix sockets, or ``None`` if not known.
  119. self.server = server
  120. #: The prefix that the application is mounted under, without a
  121. #: trailing slash. :attr:`path` comes after this.
  122. self.root_path = root_path.rstrip("/")
  123. #: The path part of the URL after :attr:`root_path`. This is the
  124. #: path used for routing within the application.
  125. self.path = "/" + path.lstrip("/")
  126. #: The part of the URL after the "?". This is the raw value, use
  127. #: :attr:`args` for the parsed values.
  128. self.query_string = query_string
  129. #: The headers received with the request.
  130. self.headers = headers
  131. #: The address of the client sending the request.
  132. self.remote_addr = remote_addr
  133. def __repr__(self) -> str:
  134. try:
  135. url = self.url
  136. except Exception as e:
  137. url = f"(invalid URL: {e})"
  138. return f"<{type(self).__name__} {url!r} [{self.method}]>"
  139. @cached_property
  140. def args(self) -> MultiDict[str, str]:
  141. """The parsed URL parameters (the part in the URL after the question
  142. mark).
  143. By default an
  144. :class:`~werkzeug.datastructures.ImmutableMultiDict`
  145. is returned from this function. This can be changed by setting
  146. :attr:`parameter_storage_class` to a different type. This might
  147. be necessary if the order of the form data is important.
  148. .. versionchanged:: 2.3
  149. Invalid bytes remain percent encoded.
  150. """
  151. return self.parameter_storage_class(
  152. parse_qsl(
  153. self.query_string.decode(),
  154. keep_blank_values=True,
  155. errors="werkzeug.url_quote",
  156. )
  157. )
  158. @cached_property
  159. def access_route(self) -> list[str]:
  160. """If a forwarded header exists this is a list of all ip addresses
  161. from the client ip to the last proxy server.
  162. """
  163. if "X-Forwarded-For" in self.headers:
  164. return self.list_storage_class(
  165. parse_list_header(self.headers["X-Forwarded-For"])
  166. )
  167. elif self.remote_addr is not None:
  168. return self.list_storage_class([self.remote_addr])
  169. return self.list_storage_class()
  170. @cached_property
  171. def full_path(self) -> str:
  172. """Requested path, including the query string."""
  173. return f"{self.path}?{self.query_string.decode()}"
  174. @property
  175. def is_secure(self) -> bool:
  176. """``True`` if the request was made with a secure protocol
  177. (HTTPS or WSS).
  178. """
  179. return self.scheme in {"https", "wss"}
  180. @cached_property
  181. def url(self) -> str:
  182. """The full request URL with the scheme, host, root path, path,
  183. and query string."""
  184. return get_current_url(
  185. self.scheme, self.host, self.root_path, self.path, self.query_string
  186. )
  187. @cached_property
  188. def base_url(self) -> str:
  189. """Like :attr:`url` but without the query string."""
  190. return get_current_url(self.scheme, self.host, self.root_path, self.path)
  191. @cached_property
  192. def root_url(self) -> str:
  193. """The request URL scheme, host, and root path. This is the root
  194. that the application is accessed from.
  195. """
  196. return get_current_url(self.scheme, self.host, self.root_path)
  197. @cached_property
  198. def host_url(self) -> str:
  199. """The request URL scheme and host only."""
  200. return get_current_url(self.scheme, self.host)
  201. @cached_property
  202. def host(self) -> str:
  203. """The host name the request was made to, including the port if
  204. it's non-standard. Validated with :attr:`trusted_hosts`.
  205. """
  206. return get_host(
  207. self.scheme, self.headers.get("host"), self.server, self.trusted_hosts
  208. )
  209. @cached_property
  210. def cookies(self) -> ImmutableMultiDict[str, str]:
  211. """A :class:`dict` with the contents of all cookies transmitted with
  212. the request."""
  213. wsgi_combined_cookie = ";".join(self.headers.getlist("Cookie"))
  214. return parse_cookie( # type: ignore
  215. wsgi_combined_cookie, cls=self.dict_storage_class
  216. )
  217. # Common Descriptors
  218. content_type = header_property[str](
  219. "Content-Type",
  220. doc="""The Content-Type entity-header field indicates the media
  221. type of the entity-body sent to the recipient or, in the case of
  222. the HEAD method, the media type that would have been sent had
  223. the request been a GET.""",
  224. read_only=True,
  225. )
  226. @cached_property
  227. def content_length(self) -> int | None:
  228. """The Content-Length entity-header field indicates the size of the
  229. entity-body in bytes or, in the case of the HEAD method, the size of
  230. the entity-body that would have been sent had the request been a
  231. GET.
  232. """
  233. return get_content_length(
  234. http_content_length=self.headers.get("Content-Length"),
  235. http_transfer_encoding=self.headers.get("Transfer-Encoding"),
  236. )
  237. content_encoding = header_property[str](
  238. "Content-Encoding",
  239. doc="""The Content-Encoding entity-header field is used as a
  240. modifier to the media-type. When present, its value indicates
  241. what additional content codings have been applied to the
  242. entity-body, and thus what decoding mechanisms must be applied
  243. in order to obtain the media-type referenced by the Content-Type
  244. header field.
  245. .. versionadded:: 0.9""",
  246. read_only=True,
  247. )
  248. content_md5 = header_property[str](
  249. "Content-MD5",
  250. doc="""The Content-MD5 entity-header field, as defined in
  251. RFC 1864, is an MD5 digest of the entity-body for the purpose of
  252. providing an end-to-end message integrity check (MIC) of the
  253. entity-body. (Note: a MIC is good for detecting accidental
  254. modification of the entity-body in transit, but is not proof
  255. against malicious attacks.)
  256. .. versionadded:: 0.9""",
  257. read_only=True,
  258. )
  259. referrer = header_property[str](
  260. "Referer",
  261. doc="""The Referer[sic] request-header field allows the client
  262. to specify, for the server's benefit, the address (URI) of the
  263. resource from which the Request-URI was obtained (the
  264. "referrer", although the header field is misspelled).""",
  265. read_only=True,
  266. )
  267. date = header_property(
  268. "Date",
  269. None,
  270. parse_date,
  271. doc="""The Date general-header field represents the date and
  272. time at which the message was originated, having the same
  273. semantics as orig-date in RFC 822.
  274. .. versionchanged:: 2.0
  275. The datetime object is timezone-aware.
  276. """,
  277. read_only=True,
  278. )
  279. max_forwards = header_property(
  280. "Max-Forwards",
  281. None,
  282. int,
  283. doc="""The Max-Forwards request-header field provides a
  284. mechanism with the TRACE and OPTIONS methods to limit the number
  285. of proxies or gateways that can forward the request to the next
  286. inbound server.""",
  287. read_only=True,
  288. )
  289. def _parse_content_type(self) -> None:
  290. if not hasattr(self, "_parsed_content_type"):
  291. self._parsed_content_type = parse_options_header(
  292. self.headers.get("Content-Type", "")
  293. )
  294. @property
  295. def mimetype(self) -> str:
  296. """Like :attr:`content_type`, but without parameters (eg, without
  297. charset, type etc.) and always lowercase. For example if the content
  298. type is ``text/HTML; charset=utf-8`` the mimetype would be
  299. ``'text/html'``.
  300. """
  301. self._parse_content_type()
  302. return self._parsed_content_type[0].lower()
  303. @property
  304. def mimetype_params(self) -> dict[str, str]:
  305. """The mimetype parameters as dict. For example if the content
  306. type is ``text/html; charset=utf-8`` the params would be
  307. ``{'charset': 'utf-8'}``.
  308. """
  309. self._parse_content_type()
  310. return self._parsed_content_type[1]
  311. @cached_property
  312. def pragma(self) -> HeaderSet:
  313. """The Pragma general-header field is used to include
  314. implementation-specific directives that might apply to any recipient
  315. along the request/response chain. All pragma directives specify
  316. optional behavior from the viewpoint of the protocol; however, some
  317. systems MAY require that behavior be consistent with the directives.
  318. """
  319. return parse_set_header(self.headers.get("Pragma", ""))
  320. # Accept
  321. @cached_property
  322. def accept_mimetypes(self) -> MIMEAccept:
  323. """List of mimetypes this client supports as
  324. :class:`~werkzeug.datastructures.MIMEAccept` object.
  325. """
  326. return parse_accept_header(self.headers.get("Accept"), MIMEAccept)
  327. @cached_property
  328. def accept_charsets(self) -> CharsetAccept:
  329. """List of charsets this client supports as
  330. :class:`~werkzeug.datastructures.CharsetAccept` object.
  331. """
  332. return parse_accept_header(self.headers.get("Accept-Charset"), CharsetAccept)
  333. @cached_property
  334. def accept_encodings(self) -> Accept:
  335. """List of encodings this client accepts. Encodings in a HTTP term
  336. are compression encodings such as gzip. For charsets have a look at
  337. :attr:`accept_charset`.
  338. """
  339. return parse_accept_header(self.headers.get("Accept-Encoding"))
  340. @cached_property
  341. def accept_languages(self) -> LanguageAccept:
  342. """List of languages this client accepts as
  343. :class:`~werkzeug.datastructures.LanguageAccept` object.
  344. .. versionchanged 0.5
  345. In previous versions this was a regular
  346. :class:`~werkzeug.datastructures.Accept` object.
  347. """
  348. return parse_accept_header(self.headers.get("Accept-Language"), LanguageAccept)
  349. # ETag
  350. @cached_property
  351. def cache_control(self) -> RequestCacheControl:
  352. """A :class:`~werkzeug.datastructures.RequestCacheControl` object
  353. for the incoming cache control headers.
  354. """
  355. cache_control = self.headers.get("Cache-Control")
  356. return parse_cache_control_header(cache_control, None, RequestCacheControl)
  357. @cached_property
  358. def if_match(self) -> ETags:
  359. """An object containing all the etags in the `If-Match` header.
  360. :rtype: :class:`~werkzeug.datastructures.ETags`
  361. """
  362. return parse_etags(self.headers.get("If-Match"))
  363. @cached_property
  364. def if_none_match(self) -> ETags:
  365. """An object containing all the etags in the `If-None-Match` header.
  366. :rtype: :class:`~werkzeug.datastructures.ETags`
  367. """
  368. return parse_etags(self.headers.get("If-None-Match"))
  369. @cached_property
  370. def if_modified_since(self) -> datetime | None:
  371. """The parsed `If-Modified-Since` header as a datetime object.
  372. .. versionchanged:: 2.0
  373. The datetime object is timezone-aware.
  374. """
  375. return parse_date(self.headers.get("If-Modified-Since"))
  376. @cached_property
  377. def if_unmodified_since(self) -> datetime | None:
  378. """The parsed `If-Unmodified-Since` header as a datetime object.
  379. .. versionchanged:: 2.0
  380. The datetime object is timezone-aware.
  381. """
  382. return parse_date(self.headers.get("If-Unmodified-Since"))
  383. @cached_property
  384. def if_range(self) -> IfRange:
  385. """The parsed ``If-Range`` header.
  386. .. versionchanged:: 2.0
  387. ``IfRange.date`` is timezone-aware.
  388. .. versionadded:: 0.7
  389. """
  390. return parse_if_range_header(self.headers.get("If-Range"))
  391. @cached_property
  392. def range(self) -> Range | None:
  393. """The parsed `Range` header.
  394. .. versionadded:: 0.7
  395. :rtype: :class:`~werkzeug.datastructures.Range`
  396. """
  397. return parse_range_header(self.headers.get("Range"))
  398. # User Agent
  399. @cached_property
  400. def user_agent(self) -> UserAgent:
  401. """The user agent. Use ``user_agent.string`` to get the header
  402. value. Set :attr:`user_agent_class` to a subclass of
  403. :class:`~werkzeug.user_agent.UserAgent` to provide parsing for
  404. the other properties or other extended data.
  405. .. versionchanged:: 2.1
  406. The built-in parser was removed. Set ``user_agent_class`` to a ``UserAgent``
  407. subclass to parse data from the string.
  408. """
  409. return self.user_agent_class(self.headers.get("User-Agent", ""))
  410. # Authorization
  411. @cached_property
  412. def authorization(self) -> Authorization | None:
  413. """The ``Authorization`` header parsed into an :class:`.Authorization` object.
  414. ``None`` if the header is not present.
  415. .. versionchanged:: 2.3
  416. :class:`Authorization` is no longer a ``dict``. The ``token`` attribute
  417. was added for auth schemes that use a token instead of parameters.
  418. """
  419. return Authorization.from_header(self.headers.get("Authorization"))
  420. # CORS
  421. origin = header_property[str](
  422. "Origin",
  423. doc=(
  424. "The host that the request originated from. Set"
  425. " :attr:`~CORSResponseMixin.access_control_allow_origin` on"
  426. " the response to indicate which origins are allowed."
  427. ),
  428. read_only=True,
  429. )
  430. access_control_request_headers = header_property(
  431. "Access-Control-Request-Headers",
  432. load_func=parse_set_header,
  433. doc=(
  434. "Sent with a preflight request to indicate which headers"
  435. " will be sent with the cross origin request. Set"
  436. " :attr:`~CORSResponseMixin.access_control_allow_headers`"
  437. " on the response to indicate which headers are allowed."
  438. ),
  439. read_only=True,
  440. )
  441. access_control_request_method = header_property[str](
  442. "Access-Control-Request-Method",
  443. doc=(
  444. "Sent with a preflight request to indicate which method"
  445. " will be used for the cross origin request. Set"
  446. " :attr:`~CORSResponseMixin.access_control_allow_methods`"
  447. " on the response to indicate which methods are allowed."
  448. ),
  449. read_only=True,
  450. )
  451. @property
  452. def is_json(self) -> bool:
  453. """Check if the mimetype indicates JSON data, either
  454. :mimetype:`application/json` or :mimetype:`application/*+json`.
  455. """
  456. mt = self.mimetype
  457. return (
  458. mt == "application/json"
  459. or mt.startswith("application/")
  460. and mt.endswith("+json")
  461. )