request.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. from __future__ import annotations
  2. import collections.abc as cabc
  3. import functools
  4. import json
  5. import typing as t
  6. from io import BytesIO
  7. from .._internal import _wsgi_decoding_dance
  8. from ..datastructures import CombinedMultiDict
  9. from ..datastructures import EnvironHeaders
  10. from ..datastructures import FileStorage
  11. from ..datastructures import ImmutableMultiDict
  12. from ..datastructures import iter_multi_items
  13. from ..datastructures import MultiDict
  14. from ..exceptions import BadRequest
  15. from ..exceptions import UnsupportedMediaType
  16. from ..formparser import default_stream_factory
  17. from ..formparser import FormDataParser
  18. from ..sansio.request import Request as _SansIORequest
  19. from ..utils import cached_property
  20. from ..utils import environ_property
  21. from ..wsgi import _get_server
  22. from ..wsgi import get_input_stream
  23. if t.TYPE_CHECKING:
  24. from _typeshed.wsgi import WSGIApplication
  25. from _typeshed.wsgi import WSGIEnvironment
  26. class Request(_SansIORequest):
  27. """Represents an incoming WSGI HTTP request, with headers and body
  28. taken from the WSGI environment. Has properties and methods for
  29. using the functionality defined by various HTTP specs. The data in
  30. requests object is read-only.
  31. Text data is assumed to use UTF-8 encoding, which should be true for
  32. the vast majority of modern clients. Using an encoding set by the
  33. client is unsafe in Python due to extra encodings it provides, such
  34. as ``zip``. To change the assumed encoding, subclass and replace
  35. :attr:`charset`.
  36. :param environ: The WSGI environ is generated by the WSGI server and
  37. contains information about the server configuration and client
  38. request.
  39. :param populate_request: Add this request object to the WSGI environ
  40. as ``environ['werkzeug.request']``. Can be useful when
  41. debugging.
  42. :param shallow: Makes reading from :attr:`stream` (and any method
  43. that would read from it) raise a :exc:`RuntimeError`. Useful to
  44. prevent consuming the form data in middleware, which would make
  45. it unavailable to the final application.
  46. .. versionchanged:: 3.0
  47. The ``charset``, ``url_charset``, and ``encoding_errors`` parameters
  48. were removed.
  49. .. versionchanged:: 2.1
  50. Old ``BaseRequest`` and mixin classes were removed.
  51. .. versionchanged:: 2.1
  52. Remove the ``disable_data_descriptor`` attribute.
  53. .. versionchanged:: 2.0
  54. Combine ``BaseRequest`` and mixins into a single ``Request``
  55. class.
  56. .. versionchanged:: 0.5
  57. Read-only mode is enforced with immutable classes for all data.
  58. """
  59. #: the maximum content length. This is forwarded to the form data
  60. #: parsing function (:func:`parse_form_data`). When set and the
  61. #: :attr:`form` or :attr:`files` attribute is accessed and the
  62. #: parsing fails because more than the specified value is transmitted
  63. #: a :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised.
  64. #:
  65. #: .. versionadded:: 0.5
  66. max_content_length: int | None = None
  67. #: the maximum form field size. This is forwarded to the form data
  68. #: parsing function (:func:`parse_form_data`). When set and the
  69. #: :attr:`form` or :attr:`files` attribute is accessed and the
  70. #: data in memory for post data is longer than the specified value a
  71. #: :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised.
  72. #:
  73. #: .. versionadded:: 0.5
  74. max_form_memory_size: int | None = None
  75. #: The maximum number of multipart parts to parse, passed to
  76. #: :attr:`form_data_parser_class`. Parsing form data with more than this
  77. #: many parts will raise :exc:`~.RequestEntityTooLarge`.
  78. #:
  79. #: .. versionadded:: 2.2.3
  80. max_form_parts = 1000
  81. #: The form data parser that should be used. Can be replaced to customize
  82. #: the form date parsing.
  83. form_data_parser_class: type[FormDataParser] = FormDataParser
  84. #: The WSGI environment containing HTTP headers and information from
  85. #: the WSGI server.
  86. environ: WSGIEnvironment
  87. #: Set when creating the request object. If ``True``, reading from
  88. #: the request body will cause a ``RuntimeException``. Useful to
  89. #: prevent modifying the stream from middleware.
  90. shallow: bool
  91. def __init__(
  92. self,
  93. environ: WSGIEnvironment,
  94. populate_request: bool = True,
  95. shallow: bool = False,
  96. ) -> None:
  97. super().__init__(
  98. method=environ.get("REQUEST_METHOD", "GET"),
  99. scheme=environ.get("wsgi.url_scheme", "http"),
  100. server=_get_server(environ),
  101. root_path=_wsgi_decoding_dance(environ.get("SCRIPT_NAME") or ""),
  102. path=_wsgi_decoding_dance(environ.get("PATH_INFO") or ""),
  103. query_string=environ.get("QUERY_STRING", "").encode("latin1"),
  104. headers=EnvironHeaders(environ),
  105. remote_addr=environ.get("REMOTE_ADDR"),
  106. )
  107. self.environ = environ
  108. self.shallow = shallow
  109. if populate_request and not shallow:
  110. self.environ["werkzeug.request"] = self
  111. @classmethod
  112. def from_values(cls, *args: t.Any, **kwargs: t.Any) -> Request:
  113. """Create a new request object based on the values provided. If
  114. environ is given missing values are filled from there. This method is
  115. useful for small scripts when you need to simulate a request from an URL.
  116. Do not use this method for unittesting, there is a full featured client
  117. object (:class:`Client`) that allows to create multipart requests,
  118. support for cookies etc.
  119. This accepts the same options as the
  120. :class:`~werkzeug.test.EnvironBuilder`.
  121. .. versionchanged:: 0.5
  122. This method now accepts the same arguments as
  123. :class:`~werkzeug.test.EnvironBuilder`. Because of this the
  124. `environ` parameter is now called `environ_overrides`.
  125. :return: request object
  126. """
  127. from ..test import EnvironBuilder
  128. builder = EnvironBuilder(*args, **kwargs)
  129. try:
  130. return builder.get_request(cls)
  131. finally:
  132. builder.close()
  133. @classmethod
  134. def application(cls, f: t.Callable[[Request], WSGIApplication]) -> WSGIApplication:
  135. """Decorate a function as responder that accepts the request as
  136. the last argument. This works like the :func:`responder`
  137. decorator but the function is passed the request object as the
  138. last argument and the request object will be closed
  139. automatically::
  140. @Request.application
  141. def my_wsgi_app(request):
  142. return Response('Hello World!')
  143. As of Werkzeug 0.14 HTTP exceptions are automatically caught and
  144. converted to responses instead of failing.
  145. :param f: the WSGI callable to decorate
  146. :return: a new WSGI callable
  147. """
  148. #: return a callable that wraps the -2nd argument with the request
  149. #: and calls the function with all the arguments up to that one and
  150. #: the request. The return value is then called with the latest
  151. #: two arguments. This makes it possible to use this decorator for
  152. #: both standalone WSGI functions as well as bound methods and
  153. #: partially applied functions.
  154. from ..exceptions import HTTPException
  155. @functools.wraps(f)
  156. def application(*args: t.Any) -> cabc.Iterable[bytes]:
  157. request = cls(args[-2])
  158. with request:
  159. try:
  160. resp = f(*args[:-2] + (request,))
  161. except HTTPException as e:
  162. resp = t.cast("WSGIApplication", e.get_response(args[-2]))
  163. return resp(*args[-2:])
  164. return t.cast("WSGIApplication", application)
  165. def _get_file_stream(
  166. self,
  167. total_content_length: int | None,
  168. content_type: str | None,
  169. filename: str | None = None,
  170. content_length: int | None = None,
  171. ) -> t.IO[bytes]:
  172. """Called to get a stream for the file upload.
  173. This must provide a file-like class with `read()`, `readline()`
  174. and `seek()` methods that is both writeable and readable.
  175. The default implementation returns a temporary file if the total
  176. content length is higher than 500KB. Because many browsers do not
  177. provide a content length for the files only the total content
  178. length matters.
  179. :param total_content_length: the total content length of all the
  180. data in the request combined. This value
  181. is guaranteed to be there.
  182. :param content_type: the mimetype of the uploaded file.
  183. :param filename: the filename of the uploaded file. May be `None`.
  184. :param content_length: the length of this file. This value is usually
  185. not provided because webbrowsers do not provide
  186. this value.
  187. """
  188. return default_stream_factory(
  189. total_content_length=total_content_length,
  190. filename=filename,
  191. content_type=content_type,
  192. content_length=content_length,
  193. )
  194. @property
  195. def want_form_data_parsed(self) -> bool:
  196. """``True`` if the request method carries content. By default
  197. this is true if a ``Content-Type`` is sent.
  198. .. versionadded:: 0.8
  199. """
  200. return bool(self.environ.get("CONTENT_TYPE"))
  201. def make_form_data_parser(self) -> FormDataParser:
  202. """Creates the form data parser. Instantiates the
  203. :attr:`form_data_parser_class` with some parameters.
  204. .. versionadded:: 0.8
  205. """
  206. return self.form_data_parser_class(
  207. stream_factory=self._get_file_stream,
  208. max_form_memory_size=self.max_form_memory_size,
  209. max_content_length=self.max_content_length,
  210. max_form_parts=self.max_form_parts,
  211. cls=self.parameter_storage_class,
  212. )
  213. def _load_form_data(self) -> None:
  214. """Method used internally to retrieve submitted data. After calling
  215. this sets `form` and `files` on the request object to multi dicts
  216. filled with the incoming form data. As a matter of fact the input
  217. stream will be empty afterwards. You can also call this method to
  218. force the parsing of the form data.
  219. .. versionadded:: 0.8
  220. """
  221. # abort early if we have already consumed the stream
  222. if "form" in self.__dict__:
  223. return
  224. if self.want_form_data_parsed:
  225. parser = self.make_form_data_parser()
  226. data = parser.parse(
  227. self._get_stream_for_parsing(),
  228. self.mimetype,
  229. self.content_length,
  230. self.mimetype_params,
  231. )
  232. else:
  233. data = (
  234. self.stream,
  235. self.parameter_storage_class(),
  236. self.parameter_storage_class(),
  237. )
  238. # inject the values into the instance dict so that we bypass
  239. # our cached_property non-data descriptor.
  240. d = self.__dict__
  241. d["stream"], d["form"], d["files"] = data
  242. def _get_stream_for_parsing(self) -> t.IO[bytes]:
  243. """This is the same as accessing :attr:`stream` with the difference
  244. that if it finds cached data from calling :meth:`get_data` first it
  245. will create a new stream out of the cached data.
  246. .. versionadded:: 0.9.3
  247. """
  248. cached_data = getattr(self, "_cached_data", None)
  249. if cached_data is not None:
  250. return BytesIO(cached_data)
  251. return self.stream
  252. def close(self) -> None:
  253. """Closes associated resources of this request object. This
  254. closes all file handles explicitly. You can also use the request
  255. object in a with statement which will automatically close it.
  256. .. versionadded:: 0.9
  257. """
  258. files = self.__dict__.get("files")
  259. for _key, value in iter_multi_items(files or ()):
  260. value.close()
  261. def __enter__(self) -> Request:
  262. return self
  263. def __exit__(self, exc_type, exc_value, tb) -> None: # type: ignore
  264. self.close()
  265. @cached_property
  266. def stream(self) -> t.IO[bytes]:
  267. """The WSGI input stream, with safety checks. This stream can only be consumed
  268. once.
  269. Use :meth:`get_data` to get the full data as bytes or text. The :attr:`data`
  270. attribute will contain the full bytes only if they do not represent form data.
  271. The :attr:`form` attribute will contain the parsed form data in that case.
  272. Unlike :attr:`input_stream`, this stream guards against infinite streams or
  273. reading past :attr:`content_length` or :attr:`max_content_length`.
  274. If ``max_content_length`` is set, it can be enforced on streams if
  275. ``wsgi.input_terminated`` is set. Otherwise, an empty stream is returned.
  276. If the limit is reached before the underlying stream is exhausted (such as a
  277. file that is too large, or an infinite stream), the remaining contents of the
  278. stream cannot be read safely. Depending on how the server handles this, clients
  279. may show a "connection reset" failure instead of seeing the 413 response.
  280. .. versionchanged:: 2.3
  281. Check ``max_content_length`` preemptively and while reading.
  282. .. versionchanged:: 0.9
  283. The stream is always set (but may be consumed) even if form parsing was
  284. accessed first.
  285. """
  286. if self.shallow:
  287. raise RuntimeError(
  288. "This request was created with 'shallow=True', reading"
  289. " from the input stream is disabled."
  290. )
  291. return get_input_stream(
  292. self.environ, max_content_length=self.max_content_length
  293. )
  294. input_stream = environ_property[t.IO[bytes]](
  295. "wsgi.input",
  296. doc="""The raw WSGI input stream, without any safety checks.
  297. This is dangerous to use. It does not guard against infinite streams or reading
  298. past :attr:`content_length` or :attr:`max_content_length`.
  299. Use :attr:`stream` instead.
  300. """,
  301. )
  302. @cached_property
  303. def data(self) -> bytes:
  304. """The raw data read from :attr:`stream`. Will be empty if the request
  305. represents form data.
  306. To get the raw data even if it represents form data, use :meth:`get_data`.
  307. """
  308. return self.get_data(parse_form_data=True)
  309. @t.overload
  310. def get_data( # type: ignore
  311. self,
  312. cache: bool = True,
  313. as_text: t.Literal[False] = False,
  314. parse_form_data: bool = False,
  315. ) -> bytes: ...
  316. @t.overload
  317. def get_data(
  318. self,
  319. cache: bool = True,
  320. as_text: t.Literal[True] = ...,
  321. parse_form_data: bool = False,
  322. ) -> str: ...
  323. def get_data(
  324. self, cache: bool = True, as_text: bool = False, parse_form_data: bool = False
  325. ) -> bytes | str:
  326. """This reads the buffered incoming data from the client into one
  327. bytes object. By default this is cached but that behavior can be
  328. changed by setting `cache` to `False`.
  329. Usually it's a bad idea to call this method without checking the
  330. content length first as a client could send dozens of megabytes or more
  331. to cause memory problems on the server.
  332. Note that if the form data was already parsed this method will not
  333. return anything as form data parsing does not cache the data like
  334. this method does. To implicitly invoke form data parsing function
  335. set `parse_form_data` to `True`. When this is done the return value
  336. of this method will be an empty string if the form parser handles
  337. the data. This generally is not necessary as if the whole data is
  338. cached (which is the default) the form parser will used the cached
  339. data to parse the form data. Please be generally aware of checking
  340. the content length first in any case before calling this method
  341. to avoid exhausting server memory.
  342. If `as_text` is set to `True` the return value will be a decoded
  343. string.
  344. .. versionadded:: 0.9
  345. """
  346. rv = getattr(self, "_cached_data", None)
  347. if rv is None:
  348. if parse_form_data:
  349. self._load_form_data()
  350. rv = self.stream.read()
  351. if cache:
  352. self._cached_data = rv
  353. if as_text:
  354. rv = rv.decode(errors="replace")
  355. return rv
  356. @cached_property
  357. def form(self) -> ImmutableMultiDict[str, str]:
  358. """The form parameters. By default an
  359. :class:`~werkzeug.datastructures.ImmutableMultiDict`
  360. is returned from this function. This can be changed by setting
  361. :attr:`parameter_storage_class` to a different type. This might
  362. be necessary if the order of the form data is important.
  363. Please keep in mind that file uploads will not end up here, but instead
  364. in the :attr:`files` attribute.
  365. .. versionchanged:: 0.9
  366. Previous to Werkzeug 0.9 this would only contain form data for POST
  367. and PUT requests.
  368. """
  369. self._load_form_data()
  370. return self.form
  371. @cached_property
  372. def values(self) -> CombinedMultiDict[str, str]:
  373. """A :class:`werkzeug.datastructures.CombinedMultiDict` that
  374. combines :attr:`args` and :attr:`form`.
  375. For GET requests, only ``args`` are present, not ``form``.
  376. .. versionchanged:: 2.0
  377. For GET requests, only ``args`` are present, not ``form``.
  378. """
  379. sources = [self.args]
  380. if self.method != "GET":
  381. # GET requests can have a body, and some caching proxies
  382. # might not treat that differently than a normal GET
  383. # request, allowing form data to "invisibly" affect the
  384. # cache without indication in the query string / URL.
  385. sources.append(self.form)
  386. args = []
  387. for d in sources:
  388. if not isinstance(d, MultiDict):
  389. d = MultiDict(d)
  390. args.append(d)
  391. return CombinedMultiDict(args)
  392. @cached_property
  393. def files(self) -> ImmutableMultiDict[str, FileStorage]:
  394. """:class:`~werkzeug.datastructures.MultiDict` object containing
  395. all uploaded files. Each key in :attr:`files` is the name from the
  396. ``<input type="file" name="">``. Each value in :attr:`files` is a
  397. Werkzeug :class:`~werkzeug.datastructures.FileStorage` object.
  398. It basically behaves like a standard file object you know from Python,
  399. with the difference that it also has a
  400. :meth:`~werkzeug.datastructures.FileStorage.save` function that can
  401. store the file on the filesystem.
  402. Note that :attr:`files` will only contain data if the request method was
  403. POST, PUT or PATCH and the ``<form>`` that posted to the request had
  404. ``enctype="multipart/form-data"``. It will be empty otherwise.
  405. See the :class:`~werkzeug.datastructures.MultiDict` /
  406. :class:`~werkzeug.datastructures.FileStorage` documentation for
  407. more details about the used data structure.
  408. """
  409. self._load_form_data()
  410. return self.files
  411. @property
  412. def script_root(self) -> str:
  413. """Alias for :attr:`self.root_path`. ``environ["SCRIPT_ROOT"]``
  414. without a trailing slash.
  415. """
  416. return self.root_path
  417. @cached_property
  418. def url_root(self) -> str:
  419. """Alias for :attr:`root_url`. The URL with scheme, host, and
  420. root path. For example, ``https://example.com/app/``.
  421. """
  422. return self.root_url
  423. remote_user = environ_property[str](
  424. "REMOTE_USER",
  425. doc="""If the server supports user authentication, and the
  426. script is protected, this attribute contains the username the
  427. user has authenticated as.""",
  428. )
  429. is_multithread = environ_property[bool](
  430. "wsgi.multithread",
  431. doc="""boolean that is `True` if the application is served by a
  432. multithreaded WSGI server.""",
  433. )
  434. is_multiprocess = environ_property[bool](
  435. "wsgi.multiprocess",
  436. doc="""boolean that is `True` if the application is served by a
  437. WSGI server that spawns multiple processes.""",
  438. )
  439. is_run_once = environ_property[bool](
  440. "wsgi.run_once",
  441. doc="""boolean that is `True` if the application will be
  442. executed only once in a process lifetime. This is the case for
  443. CGI for example, but it's not guaranteed that the execution only
  444. happens one time.""",
  445. )
  446. # JSON
  447. #: A module or other object that has ``dumps`` and ``loads``
  448. #: functions that match the API of the built-in :mod:`json` module.
  449. json_module = json
  450. @property
  451. def json(self) -> t.Any | None:
  452. """The parsed JSON data if :attr:`mimetype` indicates JSON
  453. (:mimetype:`application/json`, see :attr:`is_json`).
  454. Calls :meth:`get_json` with default arguments.
  455. If the request content type is not ``application/json``, this
  456. will raise a 415 Unsupported Media Type error.
  457. .. versionchanged:: 2.3
  458. Raise a 415 error instead of 400.
  459. .. versionchanged:: 2.1
  460. Raise a 400 error if the content type is incorrect.
  461. """
  462. return self.get_json()
  463. # Cached values for ``(silent=False, silent=True)``. Initialized
  464. # with sentinel values.
  465. _cached_json: tuple[t.Any, t.Any] = (Ellipsis, Ellipsis)
  466. @t.overload
  467. def get_json(
  468. self, force: bool = ..., silent: t.Literal[False] = ..., cache: bool = ...
  469. ) -> t.Any: ...
  470. @t.overload
  471. def get_json(
  472. self, force: bool = ..., silent: bool = ..., cache: bool = ...
  473. ) -> t.Any | None: ...
  474. def get_json(
  475. self, force: bool = False, silent: bool = False, cache: bool = True
  476. ) -> t.Any | None:
  477. """Parse :attr:`data` as JSON.
  478. If the mimetype does not indicate JSON
  479. (:mimetype:`application/json`, see :attr:`is_json`), or parsing
  480. fails, :meth:`on_json_loading_failed` is called and
  481. its return value is used as the return value. By default this
  482. raises a 415 Unsupported Media Type resp.
  483. :param force: Ignore the mimetype and always try to parse JSON.
  484. :param silent: Silence mimetype and parsing errors, and
  485. return ``None`` instead.
  486. :param cache: Store the parsed JSON to return for subsequent
  487. calls.
  488. .. versionchanged:: 2.3
  489. Raise a 415 error instead of 400.
  490. .. versionchanged:: 2.1
  491. Raise a 400 error if the content type is incorrect.
  492. """
  493. if cache and self._cached_json[silent] is not Ellipsis:
  494. return self._cached_json[silent]
  495. if not (force or self.is_json):
  496. if not silent:
  497. return self.on_json_loading_failed(None)
  498. else:
  499. return None
  500. data = self.get_data(cache=cache)
  501. try:
  502. rv = self.json_module.loads(data)
  503. except ValueError as e:
  504. if silent:
  505. rv = None
  506. if cache:
  507. normal_rv, _ = self._cached_json
  508. self._cached_json = (normal_rv, rv)
  509. else:
  510. rv = self.on_json_loading_failed(e)
  511. if cache:
  512. _, silent_rv = self._cached_json
  513. self._cached_json = (rv, silent_rv)
  514. else:
  515. if cache:
  516. self._cached_json = (rv, rv)
  517. return rv
  518. def on_json_loading_failed(self, e: ValueError | None) -> t.Any:
  519. """Called if :meth:`get_json` fails and isn't silenced.
  520. If this method returns a value, it is used as the return value
  521. for :meth:`get_json`. The default implementation raises
  522. :exc:`~werkzeug.exceptions.BadRequest`.
  523. :param e: If parsing failed, this is the exception. It will be
  524. ``None`` if the content type wasn't ``application/json``.
  525. .. versionchanged:: 2.3
  526. Raise a 415 error instead of 400.
  527. """
  528. if e is not None:
  529. raise BadRequest(f"Failed to decode JSON object: {e}")
  530. raise UnsupportedMediaType(
  531. "Did not attempt to load JSON data because the request"
  532. " Content-Type was not 'application/json'."
  533. )