response.py 32 KB

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