request.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. from __future__ import annotations
  2. from datetime import datetime
  3. from urllib.parse import parse_qsl
  4. from ..datastructures import Accept
  5. from ..datastructures import Authorization
  6. from ..datastructures import CharsetAccept
  7. from ..datastructures import ETags
  8. from ..datastructures import Headers
  9. from ..datastructures import HeaderSet
  10. from ..datastructures import IfRange
  11. from ..datastructures import ImmutableList
  12. from ..datastructures import ImmutableMultiDict
  13. from ..datastructures import LanguageAccept
  14. from ..datastructures import MIMEAccept
  15. from ..datastructures import MultiDict
  16. from ..datastructures import Range
  17. from ..datastructures import RequestCacheControl
  18. from ..http import parse_accept_header
  19. from ..http import parse_cache_control_header
  20. from ..http import parse_date
  21. from ..http import parse_etags
  22. from ..http import parse_if_range_header
  23. from ..http import parse_list_header
  24. from ..http import parse_options_header
  25. from ..http import parse_range_header
  26. from ..http import parse_set_header
  27. from ..user_agent import UserAgent
  28. from ..utils import cached_property
  29. from ..utils import header_property
  30. from .http import parse_cookie
  31. from .utils import get_content_length
  32. from .utils import get_current_url
  33. from .utils import get_host
  34. class Request:
  35. """Represents the non-IO parts of a HTTP request, including the
  36. method, URL info, and headers.
  37. This class is not meant for general use. It should only be used when
  38. implementing WSGI, ASGI, or another HTTP application spec. Werkzeug
  39. provides a WSGI implementation at :cls:`werkzeug.wrappers.Request`.
  40. :param method: The method the request was made with, such as
  41. ``GET``.
  42. :param scheme: The URL scheme of the protocol the request used, such
  43. as ``https`` or ``wss``.
  44. :param server: The address of the server. ``(host, port)``,
  45. ``(path, None)`` for unix sockets, or ``None`` if not known.
  46. :param root_path: The prefix that the application is mounted under.
  47. This is prepended to generated URLs, but is not part of route
  48. matching.
  49. :param path: The path part of the URL after ``root_path``.
  50. :param query_string: The part of the URL after the "?".
  51. :param headers: The headers received with the request.
  52. :param remote_addr: The address of the client sending the request.
  53. .. versionchanged:: 3.0
  54. The ``charset``, ``url_charset``, and ``encoding_errors`` attributes
  55. were removed.
  56. .. versionadded:: 2.0
  57. """
  58. #: the class to use for `args` and `form`. The default is an
  59. #: :class:`~werkzeug.datastructures.ImmutableMultiDict` which supports
  60. #: multiple values per key. alternatively it makes sense to use an
  61. #: :class:`~werkzeug.datastructures.ImmutableOrderedMultiDict` which
  62. #: preserves order or a :class:`~werkzeug.datastructures.ImmutableDict`
  63. #: which is the fastest but only remembers the last key. It is also
  64. #: possible to use mutable structures, but this is not recommended.
  65. #:
  66. #: .. versionadded:: 0.6
  67. parameter_storage_class: type[MultiDict] = ImmutableMultiDict
  68. #: The type to be used for dict values from the incoming WSGI
  69. #: environment. (For example for :attr:`cookies`.) By default an
  70. #: :class:`~werkzeug.datastructures.ImmutableMultiDict` is used.
  71. #:
  72. #: .. versionchanged:: 1.0.0
  73. #: Changed to ``ImmutableMultiDict`` to support multiple values.
  74. #:
  75. #: .. versionadded:: 0.6
  76. dict_storage_class: type[MultiDict] = ImmutableMultiDict
  77. #: the type to be used for list values from the incoming WSGI environment.
  78. #: By default an :class:`~werkzeug.datastructures.ImmutableList` is used
  79. #: (for example for :attr:`access_list`).
  80. #:
  81. #: .. versionadded:: 0.6
  82. list_storage_class: type[list] = ImmutableList
  83. user_agent_class: type[UserAgent] = UserAgent
  84. """The class used and returned by the :attr:`user_agent` property to
  85. parse the header. Defaults to
  86. :class:`~werkzeug.user_agent.UserAgent`, which does no parsing. An
  87. extension can provide a subclass that uses a parser to provide other
  88. data.
  89. .. versionadded:: 2.0
  90. """
  91. #: Valid host names when handling requests. By default all hosts are
  92. #: trusted, which means that whatever the client says the host is
  93. #: will be accepted.
  94. #:
  95. #: Because ``Host`` and ``X-Forwarded-Host`` headers can be set to
  96. #: any value by a malicious client, it is recommended to either set
  97. #: this property or implement similar validation in the proxy (if
  98. #: the application is being run behind one).
  99. #:
  100. #: .. versionadded:: 0.9
  101. trusted_hosts: list[str] | None = None
  102. def __init__(
  103. self,
  104. method: str,
  105. scheme: str,
  106. server: tuple[str, int | None] | None,
  107. root_path: str,
  108. path: str,
  109. query_string: bytes,
  110. headers: Headers,
  111. remote_addr: str | None,
  112. ) -> None:
  113. #: The method the request was made with, such as ``GET``.
  114. self.method = method.upper()
  115. #: The URL scheme of the protocol the request used, such as
  116. #: ``https`` or ``wss``.
  117. self.scheme = scheme
  118. #: The address of the server. ``(host, port)``, ``(path, None)``
  119. #: for unix sockets, or ``None`` if not known.
  120. self.server = server
  121. #: The prefix that the application is mounted under, without a
  122. #: trailing slash. :attr:`path` comes after this.
  123. self.root_path = root_path.rstrip("/")
  124. #: The path part of the URL after :attr:`root_path`. This is the
  125. #: path used for routing within the application.
  126. self.path = "/" + path.lstrip("/")
  127. #: The part of the URL after the "?". This is the raw value, use
  128. #: :attr:`args` for the parsed values.
  129. self.query_string = query_string
  130. #: The headers received with the request.
  131. self.headers = headers
  132. #: The address of the client sending the request.
  133. self.remote_addr = remote_addr
  134. def __repr__(self) -> str:
  135. try:
  136. url = self.url
  137. except Exception as e:
  138. url = f"(invalid URL: {e})"
  139. return f"<{type(self).__name__} {url!r} [{self.method}]>"
  140. @cached_property
  141. def args(self) -> MultiDict[str, str]:
  142. """The parsed URL parameters (the part in the URL after the question
  143. mark).
  144. By default an
  145. :class:`~werkzeug.datastructures.ImmutableMultiDict`
  146. is returned from this function. This can be changed by setting
  147. :attr:`parameter_storage_class` to a different type. This might
  148. be necessary if the order of the form data is important.
  149. .. versionchanged:: 2.3
  150. Invalid bytes remain percent encoded.
  151. """
  152. return self.parameter_storage_class(
  153. parse_qsl(
  154. self.query_string.decode(),
  155. keep_blank_values=True,
  156. errors="werkzeug.url_quote",
  157. )
  158. )
  159. @cached_property
  160. def access_route(self) -> list[str]:
  161. """If a forwarded header exists this is a list of all ip addresses
  162. from the client ip to the last proxy server.
  163. """
  164. if "X-Forwarded-For" in self.headers:
  165. return self.list_storage_class(
  166. parse_list_header(self.headers["X-Forwarded-For"])
  167. )
  168. elif self.remote_addr is not None:
  169. return self.list_storage_class([self.remote_addr])
  170. return self.list_storage_class()
  171. @cached_property
  172. def full_path(self) -> str:
  173. """Requested path, including the query string."""
  174. return f"{self.path}?{self.query_string.decode()}"
  175. @property
  176. def is_secure(self) -> bool:
  177. """``True`` if the request was made with a secure protocol
  178. (HTTPS or WSS).
  179. """
  180. return self.scheme in {"https", "wss"}
  181. @cached_property
  182. def url(self) -> str:
  183. """The full request URL with the scheme, host, root path, path,
  184. and query string."""
  185. return get_current_url(
  186. self.scheme, self.host, self.root_path, self.path, self.query_string
  187. )
  188. @cached_property
  189. def base_url(self) -> str:
  190. """Like :attr:`url` but without the query string."""
  191. return get_current_url(self.scheme, self.host, self.root_path, self.path)
  192. @cached_property
  193. def root_url(self) -> str:
  194. """The request URL scheme, host, and root path. This is the root
  195. that the application is accessed from.
  196. """
  197. return get_current_url(self.scheme, self.host, self.root_path)
  198. @cached_property
  199. def host_url(self) -> str:
  200. """The request URL scheme and host only."""
  201. return get_current_url(self.scheme, self.host)
  202. @cached_property
  203. def host(self) -> str:
  204. """The host name the request was made to, including the port if
  205. it's non-standard. Validated with :attr:`trusted_hosts`.
  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. )