request.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. See :func:`.get_host` for a detailed explanation.
  206. """
  207. return get_host(
  208. self.scheme, self.headers.get("host"), self.server, self.trusted_hosts
  209. )
  210. @cached_property
  211. def cookies(self) -> ImmutableMultiDict[str, str]:
  212. """A :class:`dict` with the contents of all cookies transmitted with
  213. the request."""
  214. wsgi_combined_cookie = ";".join(self.headers.getlist("Cookie"))
  215. return parse_cookie( # type: ignore
  216. wsgi_combined_cookie, cls=self.dict_storage_class
  217. )
  218. # Common Descriptors
  219. content_type = header_property[str](
  220. "Content-Type",
  221. doc="""The Content-Type entity-header field indicates the media
  222. type of the entity-body sent to the recipient or, in the case of
  223. the HEAD method, the media type that would have been sent had
  224. the request been a GET.""",
  225. read_only=True,
  226. )
  227. @cached_property
  228. def content_length(self) -> int | None:
  229. """The Content-Length entity-header field indicates the size of the
  230. entity-body in bytes or, in the case of the HEAD method, the size of
  231. the entity-body that would have been sent had the request been a
  232. GET.
  233. """
  234. return get_content_length(
  235. http_content_length=self.headers.get("Content-Length"),
  236. http_transfer_encoding=self.headers.get("Transfer-Encoding"),
  237. )
  238. content_encoding = header_property[str](
  239. "Content-Encoding",
  240. doc="""The Content-Encoding entity-header field is used as a
  241. modifier to the media-type. When present, its value indicates
  242. what additional content codings have been applied to the
  243. entity-body, and thus what decoding mechanisms must be applied
  244. in order to obtain the media-type referenced by the Content-Type
  245. header field.
  246. .. versionadded:: 0.9""",
  247. read_only=True,
  248. )
  249. content_md5 = header_property[str](
  250. "Content-MD5",
  251. doc="""The Content-MD5 entity-header field, as defined in
  252. RFC 1864, is an MD5 digest of the entity-body for the purpose of
  253. providing an end-to-end message integrity check (MIC) of the
  254. entity-body. (Note: a MIC is good for detecting accidental
  255. modification of the entity-body in transit, but is not proof
  256. against malicious attacks.)
  257. .. versionadded:: 0.9""",
  258. read_only=True,
  259. )
  260. referrer = header_property[str](
  261. "Referer",
  262. doc="""The Referer[sic] request-header field allows the client
  263. to specify, for the server's benefit, the address (URI) of the
  264. resource from which the Request-URI was obtained (the
  265. "referrer", although the header field is misspelled).""",
  266. read_only=True,
  267. )
  268. date = header_property(
  269. "Date",
  270. None,
  271. parse_date,
  272. doc="""The Date general-header field represents the date and
  273. time at which the message was originated, having the same
  274. semantics as orig-date in RFC 822.
  275. .. versionchanged:: 2.0
  276. The datetime object is timezone-aware.
  277. """,
  278. read_only=True,
  279. )
  280. max_forwards = header_property(
  281. "Max-Forwards",
  282. None,
  283. int,
  284. doc="""The Max-Forwards request-header field provides a
  285. mechanism with the TRACE and OPTIONS methods to limit the number
  286. of proxies or gateways that can forward the request to the next
  287. inbound server.""",
  288. read_only=True,
  289. )
  290. def _parse_content_type(self) -> None:
  291. if not hasattr(self, "_parsed_content_type"):
  292. self._parsed_content_type = parse_options_header(
  293. self.headers.get("Content-Type", "")
  294. )
  295. @property
  296. def mimetype(self) -> str:
  297. """Like :attr:`content_type`, but without parameters (eg, without
  298. charset, type etc.) and always lowercase. For example if the content
  299. type is ``text/HTML; charset=utf-8`` the mimetype would be
  300. ``'text/html'``.
  301. """
  302. self._parse_content_type()
  303. return self._parsed_content_type[0].lower()
  304. @property
  305. def mimetype_params(self) -> dict[str, str]:
  306. """The mimetype parameters as dict. For example if the content
  307. type is ``text/html; charset=utf-8`` the params would be
  308. ``{'charset': 'utf-8'}``.
  309. """
  310. self._parse_content_type()
  311. return self._parsed_content_type[1]
  312. @cached_property
  313. def pragma(self) -> HeaderSet:
  314. """The Pragma general-header field is used to include
  315. implementation-specific directives that might apply to any recipient
  316. along the request/response chain. All pragma directives specify
  317. optional behavior from the viewpoint of the protocol; however, some
  318. systems MAY require that behavior be consistent with the directives.
  319. """
  320. return parse_set_header(self.headers.get("Pragma", ""))
  321. # Accept
  322. @cached_property
  323. def accept_mimetypes(self) -> MIMEAccept:
  324. """List of mimetypes this client supports as
  325. :class:`~werkzeug.datastructures.MIMEAccept` object.
  326. """
  327. return parse_accept_header(self.headers.get("Accept"), MIMEAccept)
  328. @cached_property
  329. def accept_charsets(self) -> CharsetAccept:
  330. """List of charsets this client supports as
  331. :class:`~werkzeug.datastructures.CharsetAccept` object.
  332. """
  333. return parse_accept_header(self.headers.get("Accept-Charset"), CharsetAccept)
  334. @cached_property
  335. def accept_encodings(self) -> Accept:
  336. """List of encodings this client accepts. Encodings in a HTTP term
  337. are compression encodings such as gzip. For charsets have a look at
  338. :attr:`accept_charset`.
  339. """
  340. return parse_accept_header(self.headers.get("Accept-Encoding"))
  341. @cached_property
  342. def accept_languages(self) -> LanguageAccept:
  343. """List of languages this client accepts as
  344. :class:`~werkzeug.datastructures.LanguageAccept` object.
  345. .. versionchanged 0.5
  346. In previous versions this was a regular
  347. :class:`~werkzeug.datastructures.Accept` object.
  348. """
  349. return parse_accept_header(self.headers.get("Accept-Language"), LanguageAccept)
  350. # ETag
  351. @cached_property
  352. def cache_control(self) -> RequestCacheControl:
  353. """A :class:`~werkzeug.datastructures.RequestCacheControl` object
  354. for the incoming cache control headers.
  355. """
  356. cache_control = self.headers.get("Cache-Control")
  357. return parse_cache_control_header(cache_control, None, RequestCacheControl)
  358. @cached_property
  359. def if_match(self) -> ETags:
  360. """An object containing all the etags in the `If-Match` header.
  361. :rtype: :class:`~werkzeug.datastructures.ETags`
  362. """
  363. return parse_etags(self.headers.get("If-Match"))
  364. @cached_property
  365. def if_none_match(self) -> ETags:
  366. """An object containing all the etags in the `If-None-Match` header.
  367. :rtype: :class:`~werkzeug.datastructures.ETags`
  368. """
  369. return parse_etags(self.headers.get("If-None-Match"))
  370. @cached_property
  371. def if_modified_since(self) -> datetime | None:
  372. """The parsed `If-Modified-Since` header as a datetime object.
  373. .. versionchanged:: 2.0
  374. The datetime object is timezone-aware.
  375. """
  376. return parse_date(self.headers.get("If-Modified-Since"))
  377. @cached_property
  378. def if_unmodified_since(self) -> datetime | None:
  379. """The parsed `If-Unmodified-Since` header as a datetime object.
  380. .. versionchanged:: 2.0
  381. The datetime object is timezone-aware.
  382. """
  383. return parse_date(self.headers.get("If-Unmodified-Since"))
  384. @cached_property
  385. def if_range(self) -> IfRange:
  386. """The parsed ``If-Range`` header.
  387. .. versionchanged:: 2.0
  388. ``IfRange.date`` is timezone-aware.
  389. .. versionadded:: 0.7
  390. """
  391. return parse_if_range_header(self.headers.get("If-Range"))
  392. @cached_property
  393. def range(self) -> Range | None:
  394. """The parsed `Range` header.
  395. .. versionadded:: 0.7
  396. :rtype: :class:`~werkzeug.datastructures.Range`
  397. """
  398. return parse_range_header(self.headers.get("Range"))
  399. # User Agent
  400. @cached_property
  401. def user_agent(self) -> UserAgent:
  402. """The user agent. Use ``user_agent.string`` to get the header
  403. value. Set :attr:`user_agent_class` to a subclass of
  404. :class:`~werkzeug.user_agent.UserAgent` to provide parsing for
  405. the other properties or other extended data.
  406. .. versionchanged:: 2.1
  407. The built-in parser was removed. Set ``user_agent_class`` to a ``UserAgent``
  408. subclass to parse data from the string.
  409. """
  410. return self.user_agent_class(self.headers.get("User-Agent", ""))
  411. # Authorization
  412. @cached_property
  413. def authorization(self) -> Authorization | None:
  414. """The ``Authorization`` header parsed into an :class:`.Authorization` object.
  415. ``None`` if the header is not present.
  416. .. versionchanged:: 2.3
  417. :class:`Authorization` is no longer a ``dict``. The ``token`` attribute
  418. was added for auth schemes that use a token instead of parameters.
  419. """
  420. return Authorization.from_header(self.headers.get("Authorization"))
  421. # CORS
  422. origin = header_property[str](
  423. "Origin",
  424. doc=(
  425. "The host that the request originated from. Set"
  426. " :attr:`~CORSResponseMixin.access_control_allow_origin` on"
  427. " the response to indicate which origins are allowed."
  428. ),
  429. read_only=True,
  430. )
  431. access_control_request_headers = header_property(
  432. "Access-Control-Request-Headers",
  433. load_func=parse_set_header,
  434. doc=(
  435. "Sent with a preflight request to indicate which headers"
  436. " will be sent with the cross origin request. Set"
  437. " :attr:`~CORSResponseMixin.access_control_allow_headers`"
  438. " on the response to indicate which headers are allowed."
  439. ),
  440. read_only=True,
  441. )
  442. access_control_request_method = header_property[str](
  443. "Access-Control-Request-Method",
  444. doc=(
  445. "Sent with a preflight request to indicate which method"
  446. " will be used for the cross origin request. Set"
  447. " :attr:`~CORSResponseMixin.access_control_allow_methods`"
  448. " on the response to indicate which methods are allowed."
  449. ),
  450. read_only=True,
  451. )
  452. @property
  453. def is_json(self) -> bool:
  454. """Check if the mimetype indicates JSON data, either
  455. :mimetype:`application/json` or :mimetype:`application/*+json`.
  456. """
  457. mt = self.mimetype
  458. return (
  459. mt == "application/json"
  460. or mt.startswith("application/")
  461. and mt.endswith("+json")
  462. )