request.py 24 KB

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