response.py 32 KB

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