request.py 21 KB

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