response.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. import json
  2. import typing
  3. import typing as t
  4. import warnings
  5. from http import HTTPStatus
  6. from .._internal import _to_bytes
  7. from ..datastructures import Headers
  8. from ..http import remove_entity_headers
  9. from ..sansio.response import Response as _SansIOResponse
  10. from ..urls import iri_to_uri
  11. from ..urls import url_join
  12. from ..utils import cached_property
  13. from ..wsgi import ClosingIterator
  14. from ..wsgi import get_current_url
  15. from werkzeug._internal import _get_environ
  16. from werkzeug.http import generate_etag
  17. from werkzeug.http import http_date
  18. from werkzeug.http import is_resource_modified
  19. from werkzeug.http import parse_etags
  20. from werkzeug.http import parse_range_header
  21. from werkzeug.wsgi import _RangeWrapper
  22. if t.TYPE_CHECKING:
  23. import typing_extensions as te
  24. from _typeshed.wsgi import StartResponse
  25. from _typeshed.wsgi import WSGIApplication
  26. from _typeshed.wsgi import WSGIEnvironment
  27. from .request import Request
  28. def _warn_if_string(iterable: t.Iterable) -> None:
  29. """Helper for the response objects to check if the iterable returned
  30. to the WSGI server is not a string.
  31. """
  32. if isinstance(iterable, str):
  33. warnings.warn(
  34. "Response iterable was set to a string. This will appear to"
  35. " work but means that the server will send the data to the"
  36. " client one character at a time. This is almost never"
  37. " intended behavior, use 'response.data' to assign strings"
  38. " to the response object.",
  39. stacklevel=2,
  40. )
  41. def _iter_encoded(
  42. iterable: t.Iterable[t.Union[str, bytes]], charset: str
  43. ) -> t.Iterator[bytes]:
  44. for item in iterable:
  45. if isinstance(item, str):
  46. yield item.encode(charset)
  47. else:
  48. yield item
  49. def _clean_accept_ranges(accept_ranges: t.Union[bool, str]) -> str:
  50. if accept_ranges is True:
  51. return "bytes"
  52. elif accept_ranges is False:
  53. return "none"
  54. elif isinstance(accept_ranges, str):
  55. return accept_ranges
  56. raise ValueError("Invalid accept_ranges value")
  57. class Response(_SansIOResponse):
  58. """Represents an outgoing WSGI HTTP response with body, status, and
  59. headers. Has properties and methods for using the functionality
  60. defined by various HTTP specs.
  61. The response body is flexible to support different use cases. The
  62. simple form is passing bytes, or a string which will be encoded as
  63. UTF-8. Passing an iterable of bytes or strings makes this a
  64. streaming response. A generator is particularly useful for building
  65. a CSV file in memory or using SSE (Server Sent Events). A file-like
  66. object is also iterable, although the
  67. :func:`~werkzeug.utils.send_file` helper should be used in that
  68. case.
  69. The response object is itself a WSGI application callable. When
  70. called (:meth:`__call__`) with ``environ`` and ``start_response``,
  71. it will pass its status and headers to ``start_response`` then
  72. return its body as an iterable.
  73. .. code-block:: python
  74. from werkzeug.wrappers.response import Response
  75. def index():
  76. return Response("Hello, World!")
  77. def application(environ, start_response):
  78. path = environ.get("PATH_INFO") or "/"
  79. if path == "/":
  80. response = index()
  81. else:
  82. response = Response("Not Found", status=404)
  83. return response(environ, start_response)
  84. :param response: The data for the body of the response. A string or
  85. bytes, or tuple or list of strings or bytes, for a fixed-length
  86. response, or any other iterable of strings or bytes for a
  87. streaming response. Defaults to an empty body.
  88. :param status: The status code for the response. Either an int, in
  89. which case the default status message is added, or a string in
  90. the form ``{code} {message}``, like ``404 Not Found``. Defaults
  91. to 200.
  92. :param headers: A :class:`~werkzeug.datastructures.Headers` object,
  93. or a list of ``(key, value)`` tuples that will be converted to a
  94. ``Headers`` object.
  95. :param mimetype: The mime type (content type without charset or
  96. other parameters) of the response. If the value starts with
  97. ``text/`` (or matches some other special cases), the charset
  98. will be added to create the ``content_type``.
  99. :param content_type: The full content type of the response.
  100. Overrides building the value from ``mimetype``.
  101. :param direct_passthrough: Pass the response body directly through
  102. as the WSGI iterable. This can be used when the body is a binary
  103. file or other iterator of bytes, to skip some unnecessary
  104. checks. Use :func:`~werkzeug.utils.send_file` instead of setting
  105. this manually.
  106. .. versionchanged:: 2.0
  107. Combine ``BaseResponse`` and mixins into a single ``Response``
  108. class. Using the old classes is deprecated and will be removed
  109. in Werkzeug 2.1.
  110. .. versionchanged:: 0.5
  111. The ``direct_passthrough`` parameter was added.
  112. """
  113. #: if set to `False` accessing properties on the response object will
  114. #: not try to consume the response iterator and convert it into a list.
  115. #:
  116. #: .. versionadded:: 0.6.2
  117. #:
  118. #: That attribute was previously called `implicit_seqence_conversion`.
  119. #: (Notice the typo). If you did use this feature, you have to adapt
  120. #: your code to the name change.
  121. implicit_sequence_conversion = True
  122. #: Should this response object correct the location header to be RFC
  123. #: conformant? This is true by default.
  124. #:
  125. #: .. versionadded:: 0.8
  126. autocorrect_location_header = True
  127. #: Should this response object automatically set the content-length
  128. #: header if possible? This is true by default.
  129. #:
  130. #: .. versionadded:: 0.8
  131. automatically_set_content_length = True
  132. #: The response body to send as the WSGI iterable. A list of strings
  133. #: or bytes represents a fixed-length response, any other iterable
  134. #: is a streaming response. Strings are encoded to bytes as UTF-8.
  135. #:
  136. #: Do not set to a plain string or bytes, that will cause sending
  137. #: the response to be very inefficient as it will iterate one byte
  138. #: at a time.
  139. response: t.Union[t.Iterable[str], t.Iterable[bytes]]
  140. def __init__(
  141. self,
  142. response: t.Optional[
  143. t.Union[t.Iterable[bytes], bytes, t.Iterable[str], str]
  144. ] = None,
  145. status: t.Optional[t.Union[int, str, HTTPStatus]] = None,
  146. headers: t.Optional[
  147. t.Union[
  148. t.Mapping[str, t.Union[str, int, t.Iterable[t.Union[str, int]]]],
  149. t.Iterable[t.Tuple[str, t.Union[str, int]]],
  150. ]
  151. ] = None,
  152. mimetype: t.Optional[str] = None,
  153. content_type: t.Optional[str] = None,
  154. direct_passthrough: bool = False,
  155. ) -> None:
  156. super().__init__(
  157. status=status,
  158. headers=headers,
  159. mimetype=mimetype,
  160. content_type=content_type,
  161. )
  162. #: Pass the response body directly through as the WSGI iterable.
  163. #: This can be used when the body is a binary file or other
  164. #: iterator of bytes, to skip some unnecessary checks. Use
  165. #: :func:`~werkzeug.utils.send_file` instead of setting this
  166. #: manually.
  167. self.direct_passthrough = direct_passthrough
  168. self._on_close: t.List[t.Callable[[], t.Any]] = []
  169. # we set the response after the headers so that if a class changes
  170. # the charset attribute, the data is set in the correct charset.
  171. if response is None:
  172. self.response = []
  173. elif isinstance(response, (str, bytes, bytearray)):
  174. self.set_data(response)
  175. else:
  176. self.response = response
  177. def call_on_close(self, func: t.Callable[[], t.Any]) -> t.Callable[[], t.Any]:
  178. """Adds a function to the internal list of functions that should
  179. be called as part of closing down the response. Since 0.7 this
  180. function also returns the function that was passed so that this
  181. can be used as a decorator.
  182. .. versionadded:: 0.6
  183. """
  184. self._on_close.append(func)
  185. return func
  186. def __repr__(self) -> str:
  187. if self.is_sequence:
  188. body_info = f"{sum(map(len, self.iter_encoded()))} bytes"
  189. else:
  190. body_info = "streamed" if self.is_streamed else "likely-streamed"
  191. return f"<{type(self).__name__} {body_info} [{self.status}]>"
  192. @classmethod
  193. def force_type(
  194. cls, response: "Response", environ: t.Optional["WSGIEnvironment"] = None
  195. ) -> "Response":
  196. """Enforce that the WSGI response is a response object of the current
  197. type. Werkzeug will use the :class:`Response` internally in many
  198. situations like the exceptions. If you call :meth:`get_response` on an
  199. exception you will get back a regular :class:`Response` object, even
  200. if you are using a custom subclass.
  201. This method can enforce a given response type, and it will also
  202. convert arbitrary WSGI callables into response objects if an environ
  203. is provided::
  204. # convert a Werkzeug response object into an instance of the
  205. # MyResponseClass subclass.
  206. response = MyResponseClass.force_type(response)
  207. # convert any WSGI application into a response object
  208. response = MyResponseClass.force_type(response, environ)
  209. This is especially useful if you want to post-process responses in
  210. the main dispatcher and use functionality provided by your subclass.
  211. Keep in mind that this will modify response objects in place if
  212. possible!
  213. :param response: a response object or wsgi application.
  214. :param environ: a WSGI environment object.
  215. :return: a response object.
  216. """
  217. if not isinstance(response, Response):
  218. if environ is None:
  219. raise TypeError(
  220. "cannot convert WSGI application into response"
  221. " objects without an environ"
  222. )
  223. from ..test import run_wsgi_app
  224. response = Response(*run_wsgi_app(response, environ))
  225. response.__class__ = cls
  226. return response
  227. @classmethod
  228. def from_app(
  229. cls, app: "WSGIApplication", environ: "WSGIEnvironment", buffered: bool = False
  230. ) -> "Response":
  231. """Create a new response object from an application output. This
  232. works best if you pass it an application that returns a generator all
  233. the time. Sometimes applications may use the `write()` callable
  234. returned by the `start_response` function. This tries to resolve such
  235. edge cases automatically. But if you don't get the expected output
  236. you should set `buffered` to `True` which enforces buffering.
  237. :param app: the WSGI application to execute.
  238. :param environ: the WSGI environment to execute against.
  239. :param buffered: set to `True` to enforce buffering.
  240. :return: a response object.
  241. """
  242. from ..test import run_wsgi_app
  243. return cls(*run_wsgi_app(app, environ, buffered))
  244. @typing.overload
  245. def get_data(self, as_text: "te.Literal[False]" = False) -> bytes:
  246. ...
  247. @typing.overload
  248. def get_data(self, as_text: "te.Literal[True]") -> str:
  249. ...
  250. def get_data(self, as_text: bool = False) -> t.Union[bytes, str]:
  251. """The string representation of the response body. Whenever you call
  252. this property the response iterable is encoded and flattened. This
  253. can lead to unwanted behavior if you stream big data.
  254. This behavior can be disabled by setting
  255. :attr:`implicit_sequence_conversion` to `False`.
  256. If `as_text` is set to `True` the return value will be a decoded
  257. string.
  258. .. versionadded:: 0.9
  259. """
  260. self._ensure_sequence()
  261. rv = b"".join(self.iter_encoded())
  262. if as_text:
  263. return rv.decode(self.charset)
  264. return rv
  265. def set_data(self, value: t.Union[bytes, str]) -> None:
  266. """Sets a new string as response. The value must be a string or
  267. bytes. If a string is set it's encoded to the charset of the
  268. response (utf-8 by default).
  269. .. versionadded:: 0.9
  270. """
  271. # if a string is set, it's encoded directly so that we
  272. # can set the content length
  273. if isinstance(value, str):
  274. value = value.encode(self.charset)
  275. else:
  276. value = bytes(value)
  277. self.response = [value]
  278. if self.automatically_set_content_length:
  279. self.headers["Content-Length"] = str(len(value))
  280. data = property(
  281. get_data,
  282. set_data,
  283. doc="A descriptor that calls :meth:`get_data` and :meth:`set_data`.",
  284. )
  285. def calculate_content_length(self) -> t.Optional[int]:
  286. """Returns the content length if available or `None` otherwise."""
  287. try:
  288. self._ensure_sequence()
  289. except RuntimeError:
  290. return None
  291. return sum(len(x) for x in self.iter_encoded())
  292. def _ensure_sequence(self, mutable: bool = False) -> None:
  293. """This method can be called by methods that need a sequence. If
  294. `mutable` is true, it will also ensure that the response sequence
  295. is a standard Python list.
  296. .. versionadded:: 0.6
  297. """
  298. if self.is_sequence:
  299. # if we need a mutable object, we ensure it's a list.
  300. if mutable and not isinstance(self.response, list):
  301. self.response = list(self.response) # type: ignore
  302. return
  303. if self.direct_passthrough:
  304. raise RuntimeError(
  305. "Attempted implicit sequence conversion but the"
  306. " response object is in direct passthrough mode."
  307. )
  308. if not self.implicit_sequence_conversion:
  309. raise RuntimeError(
  310. "The response object required the iterable to be a"
  311. " sequence, but the implicit conversion was disabled."
  312. " Call make_sequence() yourself."
  313. )
  314. self.make_sequence()
  315. def make_sequence(self) -> None:
  316. """Converts the response iterator in a list. By default this happens
  317. automatically if required. If `implicit_sequence_conversion` is
  318. disabled, this method is not automatically called and some properties
  319. might raise exceptions. This also encodes all the items.
  320. .. versionadded:: 0.6
  321. """
  322. if not self.is_sequence:
  323. # if we consume an iterable we have to ensure that the close
  324. # method of the iterable is called if available when we tear
  325. # down the response
  326. close = getattr(self.response, "close", None)
  327. self.response = list(self.iter_encoded())
  328. if close is not None:
  329. self.call_on_close(close)
  330. def iter_encoded(self) -> t.Iterator[bytes]:
  331. """Iter the response encoded with the encoding of the response.
  332. If the response object is invoked as WSGI application the return
  333. value of this method is used as application iterator unless
  334. :attr:`direct_passthrough` was activated.
  335. """
  336. if __debug__:
  337. _warn_if_string(self.response)
  338. # Encode in a separate function so that self.response is fetched
  339. # early. This allows us to wrap the response with the return
  340. # value from get_app_iter or iter_encoded.
  341. return _iter_encoded(self.response, self.charset)
  342. @property
  343. def is_streamed(self) -> bool:
  344. """If the response is streamed (the response is not an iterable with
  345. a length information) this property is `True`. In this case streamed
  346. means that there is no information about the number of iterations.
  347. This is usually `True` if a generator is passed to the response object.
  348. This is useful for checking before applying some sort of post
  349. filtering that should not take place for streamed responses.
  350. """
  351. try:
  352. len(self.response) # type: ignore
  353. except (TypeError, AttributeError):
  354. return True
  355. return False
  356. @property
  357. def is_sequence(self) -> bool:
  358. """If the iterator is buffered, this property will be `True`. A
  359. response object will consider an iterator to be buffered if the
  360. response attribute is a list or tuple.
  361. .. versionadded:: 0.6
  362. """
  363. return isinstance(self.response, (tuple, list))
  364. def close(self) -> None:
  365. """Close the wrapped response if possible. You can also use the object
  366. in a with statement which will automatically close it.
  367. .. versionadded:: 0.9
  368. Can now be used in a with statement.
  369. """
  370. if hasattr(self.response, "close"):
  371. self.response.close() # type: ignore
  372. for func in self._on_close:
  373. func()
  374. def __enter__(self) -> "Response":
  375. return self
  376. def __exit__(self, exc_type, exc_value, tb): # type: ignore
  377. self.close()
  378. def freeze(self, no_etag: None = None) -> None:
  379. """Make the response object ready to be pickled. Does the
  380. following:
  381. * Buffer the response into a list, ignoring
  382. :attr:`implicity_sequence_conversion` and
  383. :attr:`direct_passthrough`.
  384. * Set the ``Content-Length`` header.
  385. * Generate an ``ETag`` header if one is not already set.
  386. .. versionchanged:: 2.0
  387. An ``ETag`` header is added, the ``no_etag`` parameter is
  388. deprecated and will be removed in Werkzeug 2.1.
  389. .. versionchanged:: 0.6
  390. The ``Content-Length`` header is set.
  391. """
  392. # Always freeze the encoded response body, ignore
  393. # implicit_sequence_conversion and direct_passthrough.
  394. self.response = list(self.iter_encoded())
  395. self.headers["Content-Length"] = str(sum(map(len, self.response)))
  396. if no_etag is not None:
  397. warnings.warn(
  398. "The 'no_etag' parameter is deprecated and will be"
  399. " removed in Werkzeug 2.1.",
  400. DeprecationWarning,
  401. stacklevel=2,
  402. )
  403. self.add_etag()
  404. def get_wsgi_headers(self, environ: "WSGIEnvironment") -> Headers:
  405. """This is automatically called right before the response is started
  406. and returns headers modified for the given environment. It returns a
  407. copy of the headers from the response with some modifications applied
  408. if necessary.
  409. For example the location header (if present) is joined with the root
  410. URL of the environment. Also the content length is automatically set
  411. to zero here for certain status codes.
  412. .. versionchanged:: 0.6
  413. Previously that function was called `fix_headers` and modified
  414. the response object in place. Also since 0.6, IRIs in location
  415. and content-location headers are handled properly.
  416. Also starting with 0.6, Werkzeug will attempt to set the content
  417. length if it is able to figure it out on its own. This is the
  418. case if all the strings in the response iterable are already
  419. encoded and the iterable is buffered.
  420. :param environ: the WSGI environment of the request.
  421. :return: returns a new :class:`~werkzeug.datastructures.Headers`
  422. object.
  423. """
  424. headers = Headers(self.headers)
  425. location: t.Optional[str] = None
  426. content_location: t.Optional[str] = None
  427. content_length: t.Optional[t.Union[str, int]] = None
  428. status = self.status_code
  429. # iterate over the headers to find all values in one go. Because
  430. # get_wsgi_headers is used each response that gives us a tiny
  431. # speedup.
  432. for key, value in headers:
  433. ikey = key.lower()
  434. if ikey == "location":
  435. location = value
  436. elif ikey == "content-location":
  437. content_location = value
  438. elif ikey == "content-length":
  439. content_length = value
  440. # make sure the location header is an absolute URL
  441. if location is not None:
  442. old_location = location
  443. if isinstance(location, str):
  444. # Safe conversion is necessary here as we might redirect
  445. # to a broken URI scheme (for instance itms-services).
  446. location = iri_to_uri(location, safe_conversion=True)
  447. if self.autocorrect_location_header:
  448. current_url = get_current_url(environ, strip_querystring=True)
  449. if isinstance(current_url, str):
  450. current_url = iri_to_uri(current_url)
  451. location = url_join(current_url, location)
  452. if location != old_location:
  453. headers["Location"] = location
  454. # make sure the content location is a URL
  455. if content_location is not None and isinstance(content_location, str):
  456. headers["Content-Location"] = iri_to_uri(content_location)
  457. if 100 <= status < 200 or status == 204:
  458. # Per section 3.3.2 of RFC 7230, "a server MUST NOT send a
  459. # Content-Length header field in any response with a status
  460. # code of 1xx (Informational) or 204 (No Content)."
  461. headers.remove("Content-Length")
  462. elif status == 304:
  463. remove_entity_headers(headers)
  464. # if we can determine the content length automatically, we
  465. # should try to do that. But only if this does not involve
  466. # flattening the iterator or encoding of strings in the
  467. # response. We however should not do that if we have a 304
  468. # response.
  469. if (
  470. self.automatically_set_content_length
  471. and self.is_sequence
  472. and content_length is None
  473. and status not in (204, 304)
  474. and not (100 <= status < 200)
  475. ):
  476. try:
  477. content_length = sum(len(_to_bytes(x, "ascii")) for x in self.response)
  478. except UnicodeError:
  479. # Something other than bytes, can't safely figure out
  480. # the length of the response.
  481. pass
  482. else:
  483. headers["Content-Length"] = str(content_length)
  484. return headers
  485. def get_app_iter(self, environ: "WSGIEnvironment") -> t.Iterable[bytes]:
  486. """Returns the application iterator for the given environ. Depending
  487. on the request method and the current status code the return value
  488. might be an empty response rather than the one from the response.
  489. If the request method is `HEAD` or the status code is in a range
  490. where the HTTP specification requires an empty response, an empty
  491. iterable is returned.
  492. .. versionadded:: 0.6
  493. :param environ: the WSGI environment of the request.
  494. :return: a response iterable.
  495. """
  496. status = self.status_code
  497. if (
  498. environ["REQUEST_METHOD"] == "HEAD"
  499. or 100 <= status < 200
  500. or status in (204, 304)
  501. ):
  502. iterable: t.Iterable[bytes] = ()
  503. elif self.direct_passthrough:
  504. if __debug__:
  505. _warn_if_string(self.response)
  506. return self.response # type: ignore
  507. else:
  508. iterable = self.iter_encoded()
  509. return ClosingIterator(iterable, self.close)
  510. def get_wsgi_response(
  511. self, environ: "WSGIEnvironment"
  512. ) -> t.Tuple[t.Iterable[bytes], str, t.List[t.Tuple[str, str]]]:
  513. """Returns the final WSGI response as tuple. The first item in
  514. the tuple is the application iterator, the second the status and
  515. the third the list of headers. The response returned is created
  516. specially for the given environment. For example if the request
  517. method in the WSGI environment is ``'HEAD'`` the response will
  518. be empty and only the headers and status code will be present.
  519. .. versionadded:: 0.6
  520. :param environ: the WSGI environment of the request.
  521. :return: an ``(app_iter, status, headers)`` tuple.
  522. """
  523. headers = self.get_wsgi_headers(environ)
  524. app_iter = self.get_app_iter(environ)
  525. return app_iter, self.status, headers.to_wsgi_list()
  526. def __call__(
  527. self, environ: "WSGIEnvironment", start_response: "StartResponse"
  528. ) -> t.Iterable[bytes]:
  529. """Process this response as WSGI application.
  530. :param environ: the WSGI environment.
  531. :param start_response: the response callable provided by the WSGI
  532. server.
  533. :return: an application iterator
  534. """
  535. app_iter, status, headers = self.get_wsgi_response(environ)
  536. start_response(status, headers)
  537. return app_iter
  538. # JSON
  539. #: A module or other object that has ``dumps`` and ``loads``
  540. #: functions that match the API of the built-in :mod:`json` module.
  541. json_module = json
  542. @property
  543. def json(self) -> t.Optional[t.Any]:
  544. """The parsed JSON data if :attr:`mimetype` indicates JSON
  545. (:mimetype:`application/json`, see :attr:`is_json`).
  546. Calls :meth:`get_json` with default arguments.
  547. """
  548. return self.get_json()
  549. def get_json(self, force: bool = False, silent: bool = False) -> t.Optional[t.Any]:
  550. """Parse :attr:`data` as JSON. Useful during testing.
  551. If the mimetype does not indicate JSON
  552. (:mimetype:`application/json`, see :attr:`is_json`), this
  553. returns ``None``.
  554. Unlike :meth:`Request.get_json`, the result is not cached.
  555. :param force: Ignore the mimetype and always try to parse JSON.
  556. :param silent: Silence parsing errors and return ``None``
  557. instead.
  558. """
  559. if not (force or self.is_json):
  560. return None
  561. data = self.get_data()
  562. try:
  563. return self.json_module.loads(data)
  564. except ValueError:
  565. if not silent:
  566. raise
  567. return None
  568. # Stream
  569. @cached_property
  570. def stream(self) -> "ResponseStream":
  571. """The response iterable as write-only stream."""
  572. return ResponseStream(self)
  573. def _wrap_range_response(self, start: int, length: int) -> None:
  574. """Wrap existing Response in case of Range Request context."""
  575. if self.status_code == 206:
  576. self.response = _RangeWrapper(self.response, start, length) # type: ignore
  577. def _is_range_request_processable(self, environ: "WSGIEnvironment") -> bool:
  578. """Return ``True`` if `Range` header is present and if underlying
  579. resource is considered unchanged when compared with `If-Range` header.
  580. """
  581. return (
  582. "HTTP_IF_RANGE" not in environ
  583. or not is_resource_modified(
  584. environ,
  585. self.headers.get("etag"),
  586. None,
  587. self.headers.get("last-modified"),
  588. ignore_if_range=False,
  589. )
  590. ) and "HTTP_RANGE" in environ
  591. def _process_range_request(
  592. self,
  593. environ: "WSGIEnvironment",
  594. complete_length: t.Optional[int] = None,
  595. accept_ranges: t.Optional[t.Union[bool, str]] = None,
  596. ) -> bool:
  597. """Handle Range Request related headers (RFC7233). If `Accept-Ranges`
  598. header is valid, and Range Request is processable, we set the headers
  599. as described by the RFC, and wrap the underlying response in a
  600. RangeWrapper.
  601. Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise.
  602. :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
  603. if `Range` header could not be parsed or satisfied.
  604. .. versionchanged:: 2.0
  605. Returns ``False`` if the length is 0.
  606. """
  607. from ..exceptions import RequestedRangeNotSatisfiable
  608. if (
  609. accept_ranges is None
  610. or complete_length is None
  611. or complete_length == 0
  612. or not self._is_range_request_processable(environ)
  613. ):
  614. return False
  615. parsed_range = parse_range_header(environ.get("HTTP_RANGE"))
  616. if parsed_range is None:
  617. raise RequestedRangeNotSatisfiable(complete_length)
  618. range_tuple = parsed_range.range_for_length(complete_length)
  619. content_range_header = parsed_range.to_content_range_header(complete_length)
  620. if range_tuple is None or content_range_header is None:
  621. raise RequestedRangeNotSatisfiable(complete_length)
  622. content_length = range_tuple[1] - range_tuple[0]
  623. self.headers["Content-Length"] = content_length
  624. self.headers["Accept-Ranges"] = accept_ranges
  625. self.content_range = content_range_header # type: ignore
  626. self.status_code = 206
  627. self._wrap_range_response(range_tuple[0], content_length)
  628. return True
  629. def make_conditional(
  630. self,
  631. request_or_environ: t.Union["WSGIEnvironment", "Request"],
  632. accept_ranges: t.Union[bool, str] = False,
  633. complete_length: t.Optional[int] = None,
  634. ) -> "Response":
  635. """Make the response conditional to the request. This method works
  636. best if an etag was defined for the response already. The `add_etag`
  637. method can be used to do that. If called without etag just the date
  638. header is set.
  639. This does nothing if the request method in the request or environ is
  640. anything but GET or HEAD.
  641. For optimal performance when handling range requests, it's recommended
  642. that your response data object implements `seekable`, `seek` and `tell`
  643. methods as described by :py:class:`io.IOBase`. Objects returned by
  644. :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.
  645. It does not remove the body of the response because that's something
  646. the :meth:`__call__` function does for us automatically.
  647. Returns self so that you can do ``return resp.make_conditional(req)``
  648. but modifies the object in-place.
  649. :param request_or_environ: a request object or WSGI environment to be
  650. used to make the response conditional
  651. against.
  652. :param accept_ranges: This parameter dictates the value of
  653. `Accept-Ranges` header. If ``False`` (default),
  654. the header is not set. If ``True``, it will be set
  655. to ``"bytes"``. If ``None``, it will be set to
  656. ``"none"``. If it's a string, it will use this
  657. value.
  658. :param complete_length: Will be used only in valid Range Requests.
  659. It will set `Content-Range` complete length
  660. value and compute `Content-Length` real value.
  661. This parameter is mandatory for successful
  662. Range Requests completion.
  663. :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
  664. if `Range` header could not be parsed or satisfied.
  665. .. versionchanged:: 2.0
  666. Range processing is skipped if length is 0 instead of
  667. raising a 416 Range Not Satisfiable error.
  668. """
  669. environ = _get_environ(request_or_environ)
  670. if environ["REQUEST_METHOD"] in ("GET", "HEAD"):
  671. # if the date is not in the headers, add it now. We however
  672. # will not override an already existing header. Unfortunately
  673. # this header will be overriden by many WSGI servers including
  674. # wsgiref.
  675. if "date" not in self.headers:
  676. self.headers["Date"] = http_date()
  677. accept_ranges = _clean_accept_ranges(accept_ranges)
  678. is206 = self._process_range_request(environ, complete_length, accept_ranges)
  679. if not is206 and not is_resource_modified(
  680. environ,
  681. self.headers.get("etag"),
  682. None,
  683. self.headers.get("last-modified"),
  684. ):
  685. if parse_etags(environ.get("HTTP_IF_MATCH")):
  686. self.status_code = 412
  687. else:
  688. self.status_code = 304
  689. if (
  690. self.automatically_set_content_length
  691. and "content-length" not in self.headers
  692. ):
  693. length = self.calculate_content_length()
  694. if length is not None:
  695. self.headers["Content-Length"] = length
  696. return self
  697. def add_etag(self, overwrite: bool = False, weak: bool = False) -> None:
  698. """Add an etag for the current response if there is none yet.
  699. .. versionchanged:: 2.0
  700. SHA-1 is used to generate the value. MD5 may not be
  701. available in some environments.
  702. """
  703. if overwrite or "etag" not in self.headers:
  704. self.set_etag(generate_etag(self.get_data()), weak)
  705. class ResponseStream:
  706. """A file descriptor like object used by the :class:`ResponseStreamMixin` to
  707. represent the body of the stream. It directly pushes into the response
  708. iterable of the response object.
  709. """
  710. mode = "wb+"
  711. def __init__(self, response: Response):
  712. self.response = response
  713. self.closed = False
  714. def write(self, value: bytes) -> int:
  715. if self.closed:
  716. raise ValueError("I/O operation on closed file")
  717. self.response._ensure_sequence(mutable=True)
  718. self.response.response.append(value) # type: ignore
  719. self.response.headers.pop("Content-Length", None)
  720. return len(value)
  721. def writelines(self, seq: t.Iterable[bytes]) -> None:
  722. for item in seq:
  723. self.write(item)
  724. def close(self) -> None:
  725. self.closed = True
  726. def flush(self) -> None:
  727. if self.closed:
  728. raise ValueError("I/O operation on closed file")
  729. def isatty(self) -> bool:
  730. if self.closed:
  731. raise ValueError("I/O operation on closed file")
  732. return False
  733. def tell(self) -> int:
  734. self.response._ensure_sequence()
  735. return sum(map(len, self.response.response))
  736. @property
  737. def encoding(self) -> str:
  738. return self.response.charset
  739. class ResponseStreamMixin:
  740. def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
  741. warnings.warn(
  742. "'ResponseStreamMixin' is deprecated and will be removed in"
  743. " Werkzeug 2.1. 'Response' now includes the functionality"
  744. " directly.",
  745. DeprecationWarning,
  746. stacklevel=2,
  747. )
  748. super().__init__(*args, **kwargs)