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