request.py 20 KB

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