response.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. from __future__ import annotations
  2. import typing as t
  3. from datetime import datetime
  4. from datetime import timedelta
  5. from datetime import timezone
  6. from http import HTTPStatus
  7. from ..datastructures import CallbackDict
  8. from ..datastructures import ContentRange
  9. from ..datastructures import ContentSecurityPolicy
  10. from ..datastructures import Headers
  11. from ..datastructures import HeaderSet
  12. from ..datastructures import ResponseCacheControl
  13. from ..datastructures import WWWAuthenticate
  14. from ..http import COEP
  15. from ..http import COOP
  16. from ..http import dump_age
  17. from ..http import dump_cookie
  18. from ..http import dump_header
  19. from ..http import dump_options_header
  20. from ..http import http_date
  21. from ..http import HTTP_STATUS_CODES
  22. from ..http import parse_age
  23. from ..http import parse_cache_control_header
  24. from ..http import parse_content_range_header
  25. from ..http import parse_csp_header
  26. from ..http import parse_date
  27. from ..http import parse_options_header
  28. from ..http import parse_set_header
  29. from ..http import quote_etag
  30. from ..http import unquote_etag
  31. from ..utils import get_content_type
  32. from ..utils import header_property
  33. if t.TYPE_CHECKING:
  34. from ..datastructures.cache_control import _CacheControl
  35. def _set_property(name: str, doc: str | None = None) -> property:
  36. def fget(self: Response) -> HeaderSet:
  37. def on_update(header_set: HeaderSet) -> None:
  38. if not header_set and name in self.headers:
  39. del self.headers[name]
  40. elif header_set:
  41. self.headers[name] = header_set.to_header()
  42. return parse_set_header(self.headers.get(name), on_update)
  43. def fset(
  44. self: Response,
  45. value: None | (str | dict[str, str | int] | t.Iterable[str]),
  46. ) -> None:
  47. if not value:
  48. del self.headers[name]
  49. elif isinstance(value, str):
  50. self.headers[name] = value
  51. else:
  52. self.headers[name] = dump_header(value)
  53. return property(fget, fset, doc=doc)
  54. class Response:
  55. """Represents the non-IO parts of an HTTP response, specifically the
  56. status and headers but not the body.
  57. This class is not meant for general use. It should only be used when
  58. implementing WSGI, ASGI, or another HTTP application spec. Werkzeug
  59. provides a WSGI implementation at :cls:`werkzeug.wrappers.Response`.
  60. :param status: The status code for the response. Either an int, in
  61. which case the default status message is added, or a string in
  62. the form ``{code} {message}``, like ``404 Not Found``. Defaults
  63. to 200.
  64. :param headers: A :class:`~werkzeug.datastructures.Headers` object,
  65. or a list of ``(key, value)`` tuples that will be converted to a
  66. ``Headers`` object.
  67. :param mimetype: The mime type (content type without charset or
  68. other parameters) of the response. If the value starts with
  69. ``text/`` (or matches some other special cases), the charset
  70. will be added to create the ``content_type``.
  71. :param content_type: The full content type of the response.
  72. Overrides building the value from ``mimetype``.
  73. .. versionchanged:: 3.0
  74. The ``charset`` attribute was removed.
  75. .. versionadded:: 2.0
  76. """
  77. #: the default status if none is provided.
  78. default_status = 200
  79. #: the default mimetype if none is provided.
  80. default_mimetype: str | None = "text/plain"
  81. #: Warn if a cookie header exceeds this size. The default, 4093, should be
  82. #: safely `supported by most browsers <cookie_>`_. A cookie larger than
  83. #: this size will still be sent, but it may be ignored or handled
  84. #: incorrectly by some browsers. Set to 0 to disable this check.
  85. #:
  86. #: .. versionadded:: 0.13
  87. #:
  88. #: .. _`cookie`: http://browsercookielimits.squawky.net/
  89. max_cookie_size = 4093
  90. # A :class:`Headers` object representing the response headers.
  91. headers: Headers
  92. def __init__(
  93. self,
  94. status: int | str | HTTPStatus | None = None,
  95. headers: t.Mapping[str, str | t.Iterable[str]]
  96. | t.Iterable[tuple[str, str]]
  97. | None = None,
  98. mimetype: str | None = None,
  99. content_type: str | None = None,
  100. ) -> None:
  101. if isinstance(headers, Headers):
  102. self.headers = headers
  103. elif not headers:
  104. self.headers = Headers()
  105. else:
  106. self.headers = Headers(headers)
  107. if content_type is None:
  108. if mimetype is None and "content-type" not in self.headers:
  109. mimetype = self.default_mimetype
  110. if mimetype is not None:
  111. mimetype = get_content_type(mimetype, "utf-8")
  112. content_type = mimetype
  113. if content_type is not None:
  114. self.headers["Content-Type"] = content_type
  115. if status is None:
  116. status = self.default_status
  117. self.status = status # type: ignore
  118. def __repr__(self) -> str:
  119. return f"<{type(self).__name__} [{self.status}]>"
  120. @property
  121. def status_code(self) -> int:
  122. """The HTTP status code as a number."""
  123. return self._status_code
  124. @status_code.setter
  125. def status_code(self, code: int) -> None:
  126. self.status = code # type: ignore
  127. @property
  128. def status(self) -> str:
  129. """The HTTP status code as a string."""
  130. return self._status
  131. @status.setter
  132. def status(self, value: str | int | HTTPStatus) -> None:
  133. self._status, self._status_code = self._clean_status(value)
  134. def _clean_status(self, value: str | int | HTTPStatus) -> tuple[str, int]:
  135. if isinstance(value, (int, HTTPStatus)):
  136. status_code = int(value)
  137. else:
  138. value = value.strip()
  139. if not value:
  140. raise ValueError("Empty status argument")
  141. code_str, sep, _ = value.partition(" ")
  142. try:
  143. status_code = int(code_str)
  144. except ValueError:
  145. # only message
  146. return f"0 {value}", 0
  147. if sep:
  148. # code and message
  149. return value, status_code
  150. # only code, look up message
  151. try:
  152. status = f"{status_code} {HTTP_STATUS_CODES[status_code].upper()}"
  153. except KeyError:
  154. status = f"{status_code} UNKNOWN"
  155. return status, status_code
  156. def set_cookie(
  157. self,
  158. key: str,
  159. value: str = "",
  160. max_age: timedelta | int | None = None,
  161. expires: str | datetime | int | float | None = None,
  162. path: str | None = "/",
  163. domain: str | None = None,
  164. secure: bool = False,
  165. httponly: bool = False,
  166. samesite: str | None = None,
  167. partitioned: bool = False,
  168. ) -> None:
  169. """Sets a cookie.
  170. A warning is raised if the size of the cookie header exceeds
  171. :attr:`max_cookie_size`, but the header will still be set.
  172. :param key: the key (name) of the cookie to be set.
  173. :param value: the value of the cookie.
  174. :param max_age: should be a number of seconds, or `None` (default) if
  175. the cookie should last only as long as the client's
  176. browser session.
  177. :param expires: should be a `datetime` object or UNIX timestamp.
  178. :param path: limits the cookie to a given path, per default it will
  179. span the whole domain.
  180. :param domain: if you want to set a cross-domain cookie. For example,
  181. ``domain="example.com"`` will set a cookie that is
  182. readable by the domain ``www.example.com``,
  183. ``foo.example.com`` etc. Otherwise, a cookie will only
  184. be readable by the domain that set it.
  185. :param secure: If ``True``, the cookie will only be available
  186. via HTTPS.
  187. :param httponly: Disallow JavaScript access to the cookie.
  188. :param samesite: Limit the scope of the cookie to only be
  189. attached to requests that are "same-site".
  190. :param partitioned: If ``True``, the cookie will be partitioned.
  191. .. versionchanged:: 3.1
  192. The ``partitioned`` parameter was added.
  193. """
  194. self.headers.add(
  195. "Set-Cookie",
  196. dump_cookie(
  197. key,
  198. value=value,
  199. max_age=max_age,
  200. expires=expires,
  201. path=path,
  202. domain=domain,
  203. secure=secure,
  204. httponly=httponly,
  205. max_size=self.max_cookie_size,
  206. samesite=samesite,
  207. partitioned=partitioned,
  208. ),
  209. )
  210. def delete_cookie(
  211. self,
  212. key: str,
  213. path: str | None = "/",
  214. domain: str | None = None,
  215. secure: bool = False,
  216. httponly: bool = False,
  217. samesite: str | None = None,
  218. partitioned: bool = False,
  219. ) -> None:
  220. """Delete a cookie. Fails silently if key doesn't exist.
  221. :param key: the key (name) of the cookie to be deleted.
  222. :param path: if the cookie that should be deleted was limited to a
  223. path, the path has to be defined here.
  224. :param domain: if the cookie that should be deleted was limited to a
  225. domain, that domain has to be defined here.
  226. :param secure: If ``True``, the cookie will only be available
  227. via HTTPS.
  228. :param httponly: Disallow JavaScript access to the cookie.
  229. :param samesite: Limit the scope of the cookie to only be
  230. attached to requests that are "same-site".
  231. :param partitioned: If ``True``, the cookie will be partitioned.
  232. """
  233. self.set_cookie(
  234. key,
  235. expires=0,
  236. max_age=0,
  237. path=path,
  238. domain=domain,
  239. secure=secure,
  240. httponly=httponly,
  241. samesite=samesite,
  242. partitioned=partitioned,
  243. )
  244. @property
  245. def is_json(self) -> bool:
  246. """Check if the mimetype indicates JSON data, either
  247. :mimetype:`application/json` or :mimetype:`application/*+json`.
  248. """
  249. mt = self.mimetype
  250. return mt is not None and (
  251. mt == "application/json"
  252. or mt.startswith("application/")
  253. and mt.endswith("+json")
  254. )
  255. # Common Descriptors
  256. @property
  257. def mimetype(self) -> str | None:
  258. """The mimetype (content type without charset etc.)"""
  259. ct = self.headers.get("content-type")
  260. if ct:
  261. return ct.split(";")[0].strip()
  262. else:
  263. return None
  264. @mimetype.setter
  265. def mimetype(self, value: str) -> None:
  266. self.headers["Content-Type"] = get_content_type(value, "utf-8")
  267. @property
  268. def mimetype_params(self) -> dict[str, str]:
  269. """The mimetype parameters as dict. For example if the
  270. content type is ``text/html; charset=utf-8`` the params would be
  271. ``{'charset': 'utf-8'}``.
  272. .. versionadded:: 0.5
  273. """
  274. def on_update(d: CallbackDict[str, str]) -> None:
  275. self.headers["Content-Type"] = dump_options_header(self.mimetype, d)
  276. d = parse_options_header(self.headers.get("content-type", ""))[1]
  277. return CallbackDict(d, on_update)
  278. location = header_property[str](
  279. "Location",
  280. doc="""The Location response-header field is used to redirect
  281. the recipient to a location other than the Request-URI for
  282. completion of the request or identification of a new
  283. resource.""",
  284. )
  285. age = header_property(
  286. "Age",
  287. None,
  288. parse_age,
  289. dump_age, # type: ignore
  290. doc="""The Age response-header field conveys the sender's
  291. estimate of the amount of time since the response (or its
  292. revalidation) was generated at the origin server.
  293. Age values are non-negative decimal integers, representing time
  294. in seconds.""",
  295. )
  296. content_type = header_property[str](
  297. "Content-Type",
  298. doc="""The Content-Type entity-header field indicates the media
  299. type of the entity-body sent to the recipient or, in the case of
  300. the HEAD method, the media type that would have been sent had
  301. the request been a GET.""",
  302. )
  303. content_length = header_property(
  304. "Content-Length",
  305. None,
  306. int,
  307. str,
  308. doc="""The Content-Length entity-header field indicates the size
  309. of the entity-body, in decimal number of OCTETs, sent to the
  310. recipient or, in the case of the HEAD method, the size of the
  311. entity-body that would have been sent had the request been a
  312. GET.""",
  313. )
  314. content_location = header_property[str](
  315. "Content-Location",
  316. doc="""The Content-Location entity-header field MAY be used to
  317. supply the resource location for the entity enclosed in the
  318. message when that entity is accessible from a location separate
  319. from the requested resource's URI.""",
  320. )
  321. content_encoding = header_property[str](
  322. "Content-Encoding",
  323. doc="""The Content-Encoding entity-header field is used as a
  324. modifier to the media-type. When present, its value indicates
  325. what additional content codings have been applied to the
  326. entity-body, and thus what decoding mechanisms must be applied
  327. in order to obtain the media-type referenced by the Content-Type
  328. header field.""",
  329. )
  330. content_md5 = header_property[str](
  331. "Content-MD5",
  332. doc="""The Content-MD5 entity-header field, as defined in
  333. RFC 1864, is an MD5 digest of the entity-body for the purpose of
  334. providing an end-to-end message integrity check (MIC) of the
  335. entity-body. (Note: a MIC is good for detecting accidental
  336. modification of the entity-body in transit, but is not proof
  337. against malicious attacks.)""",
  338. )
  339. date = header_property(
  340. "Date",
  341. None,
  342. parse_date,
  343. http_date,
  344. doc="""The Date general-header field represents the date and
  345. time at which the message was originated, having the same
  346. semantics as orig-date in RFC 822.
  347. .. versionchanged:: 2.0
  348. The datetime object is timezone-aware.
  349. """,
  350. )
  351. expires = header_property(
  352. "Expires",
  353. None,
  354. parse_date,
  355. http_date,
  356. doc="""The Expires entity-header field gives the date/time after
  357. which the response is considered stale. A stale cache entry may
  358. not normally be returned by a cache.
  359. .. versionchanged:: 2.0
  360. The datetime object is timezone-aware.
  361. """,
  362. )
  363. last_modified = header_property(
  364. "Last-Modified",
  365. None,
  366. parse_date,
  367. http_date,
  368. doc="""The Last-Modified entity-header field indicates the date
  369. and time at which the origin server believes the variant was
  370. last modified.
  371. .. versionchanged:: 2.0
  372. The datetime object is timezone-aware.
  373. """,
  374. )
  375. @property
  376. def retry_after(self) -> datetime | None:
  377. """The Retry-After response-header field can be used with a
  378. 503 (Service Unavailable) response to indicate how long the
  379. service is expected to be unavailable to the requesting client.
  380. Time in seconds until expiration or date.
  381. .. versionchanged:: 2.0
  382. The datetime object is timezone-aware.
  383. """
  384. value = self.headers.get("retry-after")
  385. if value is None:
  386. return None
  387. try:
  388. seconds = int(value)
  389. except ValueError:
  390. return parse_date(value)
  391. return datetime.now(timezone.utc) + timedelta(seconds=seconds)
  392. @retry_after.setter
  393. def retry_after(self, value: datetime | int | str | None) -> None:
  394. if value is None:
  395. if "retry-after" in self.headers:
  396. del self.headers["retry-after"]
  397. return
  398. elif isinstance(value, datetime):
  399. value = http_date(value)
  400. else:
  401. value = str(value)
  402. self.headers["Retry-After"] = value
  403. vary = _set_property(
  404. "Vary",
  405. doc="""The Vary field value indicates the set of request-header
  406. fields that fully determines, while the response is fresh,
  407. whether a cache is permitted to use the response to reply to a
  408. subsequent request without revalidation.""",
  409. )
  410. content_language = _set_property(
  411. "Content-Language",
  412. doc="""The Content-Language entity-header field describes the
  413. natural language(s) of the intended audience for the enclosed
  414. entity. Note that this might not be equivalent to all the
  415. languages used within the entity-body.""",
  416. )
  417. allow = _set_property(
  418. "Allow",
  419. doc="""The Allow entity-header field lists the set of methods
  420. supported by the resource identified by the Request-URI. The
  421. purpose of this field is strictly to inform the recipient of
  422. valid methods associated with the resource. An Allow header
  423. field MUST be present in a 405 (Method Not Allowed)
  424. response.""",
  425. )
  426. # ETag
  427. @property
  428. def cache_control(self) -> ResponseCacheControl:
  429. """The Cache-Control general-header field is used to specify
  430. directives that MUST be obeyed by all caching mechanisms along the
  431. request/response chain.
  432. """
  433. def on_update(cache_control: _CacheControl) -> None:
  434. if not cache_control and "cache-control" in self.headers:
  435. del self.headers["cache-control"]
  436. elif cache_control:
  437. self.headers["Cache-Control"] = cache_control.to_header()
  438. return parse_cache_control_header(
  439. self.headers.get("cache-control"), on_update, ResponseCacheControl
  440. )
  441. def set_etag(self, etag: str, weak: bool = False) -> None:
  442. """Set the etag, and override the old one if there was one."""
  443. self.headers["ETag"] = quote_etag(etag, weak)
  444. def get_etag(self) -> tuple[str, bool] | tuple[None, None]:
  445. """Return a tuple in the form ``(etag, is_weak)``. If there is no
  446. ETag the return value is ``(None, None)``.
  447. """
  448. return unquote_etag(self.headers.get("ETag"))
  449. accept_ranges = header_property[str](
  450. "Accept-Ranges",
  451. doc="""The `Accept-Ranges` header. Even though the name would
  452. indicate that multiple values are supported, it must be one
  453. string token only.
  454. The values ``'bytes'`` and ``'none'`` are common.
  455. .. versionadded:: 0.7""",
  456. )
  457. @property
  458. def content_range(self) -> ContentRange:
  459. """The ``Content-Range`` header as a
  460. :class:`~werkzeug.datastructures.ContentRange` object. Available
  461. even if the header is not set.
  462. .. versionadded:: 0.7
  463. """
  464. def on_update(rng: ContentRange) -> None:
  465. if not rng:
  466. del self.headers["content-range"]
  467. else:
  468. self.headers["Content-Range"] = rng.to_header()
  469. rv = parse_content_range_header(self.headers.get("content-range"), on_update)
  470. # always provide a content range object to make the descriptor
  471. # more user friendly. It provides an unset() method that can be
  472. # used to remove the header quickly.
  473. if rv is None:
  474. rv = ContentRange(None, None, None, on_update=on_update)
  475. return rv
  476. @content_range.setter
  477. def content_range(self, value: ContentRange | str | None) -> None:
  478. if not value:
  479. del self.headers["content-range"]
  480. elif isinstance(value, str):
  481. self.headers["Content-Range"] = value
  482. else:
  483. self.headers["Content-Range"] = value.to_header()
  484. # Authorization
  485. @property
  486. def www_authenticate(self) -> WWWAuthenticate:
  487. """The ``WWW-Authenticate`` header parsed into a :class:`.WWWAuthenticate`
  488. object. Modifying the object will modify the header value.
  489. This header is not set by default. To set this header, assign an instance of
  490. :class:`.WWWAuthenticate` to this attribute.
  491. .. code-block:: python
  492. response.www_authenticate = WWWAuthenticate(
  493. "basic", {"realm": "Authentication Required"}
  494. )
  495. Multiple values for this header can be sent to give the client multiple options.
  496. Assign a list to set multiple headers. However, modifying the items in the list
  497. will not automatically update the header values, and accessing this attribute
  498. will only ever return the first value.
  499. To unset this header, assign ``None`` or use ``del``.
  500. .. versionchanged:: 2.3
  501. This attribute can be assigned to to set the header. A list can be assigned
  502. to set multiple header values. Use ``del`` to unset the header.
  503. .. versionchanged:: 2.3
  504. :class:`WWWAuthenticate` is no longer a ``dict``. The ``token`` attribute
  505. was added for auth challenges that use a token instead of parameters.
  506. """
  507. value = WWWAuthenticate.from_header(self.headers.get("WWW-Authenticate"))
  508. if value is None:
  509. value = WWWAuthenticate("basic")
  510. def on_update(value: WWWAuthenticate) -> None:
  511. self.www_authenticate = value
  512. value._on_update = on_update
  513. return value
  514. @www_authenticate.setter
  515. def www_authenticate(
  516. self, value: WWWAuthenticate | list[WWWAuthenticate] | None
  517. ) -> None:
  518. if not value: # None or empty list
  519. del self.www_authenticate
  520. elif isinstance(value, list):
  521. # Clear any existing header by setting the first item.
  522. self.headers.set("WWW-Authenticate", value[0].to_header())
  523. for item in value[1:]:
  524. # Add additional header lines for additional items.
  525. self.headers.add("WWW-Authenticate", item.to_header())
  526. else:
  527. self.headers.set("WWW-Authenticate", value.to_header())
  528. def on_update(value: WWWAuthenticate) -> None:
  529. self.www_authenticate = value
  530. # When setting a single value, allow updating it directly.
  531. value._on_update = on_update
  532. @www_authenticate.deleter
  533. def www_authenticate(self) -> None:
  534. if "WWW-Authenticate" in self.headers:
  535. del self.headers["WWW-Authenticate"]
  536. # CSP
  537. @property
  538. def content_security_policy(self) -> ContentSecurityPolicy:
  539. """The ``Content-Security-Policy`` header as a
  540. :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available
  541. even if the header is not set.
  542. The Content-Security-Policy header adds an additional layer of
  543. security to help detect and mitigate certain types of attacks.
  544. """
  545. def on_update(csp: ContentSecurityPolicy) -> None:
  546. if not csp:
  547. del self.headers["content-security-policy"]
  548. else:
  549. self.headers["Content-Security-Policy"] = csp.to_header()
  550. rv = parse_csp_header(self.headers.get("content-security-policy"), on_update)
  551. if rv is None:
  552. rv = ContentSecurityPolicy(None, on_update=on_update)
  553. return rv
  554. @content_security_policy.setter
  555. def content_security_policy(
  556. self, value: ContentSecurityPolicy | str | None
  557. ) -> None:
  558. if not value:
  559. del self.headers["content-security-policy"]
  560. elif isinstance(value, str):
  561. self.headers["Content-Security-Policy"] = value
  562. else:
  563. self.headers["Content-Security-Policy"] = value.to_header()
  564. @property
  565. def content_security_policy_report_only(self) -> ContentSecurityPolicy:
  566. """The ``Content-Security-policy-report-only`` header as a
  567. :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available
  568. even if the header is not set.
  569. The Content-Security-Policy-Report-Only header adds a csp policy
  570. that is not enforced but is reported thereby helping detect
  571. certain types of attacks.
  572. """
  573. def on_update(csp: ContentSecurityPolicy) -> None:
  574. if not csp:
  575. del self.headers["content-security-policy-report-only"]
  576. else:
  577. self.headers["Content-Security-policy-report-only"] = csp.to_header()
  578. rv = parse_csp_header(
  579. self.headers.get("content-security-policy-report-only"), on_update
  580. )
  581. if rv is None:
  582. rv = ContentSecurityPolicy(None, on_update=on_update)
  583. return rv
  584. @content_security_policy_report_only.setter
  585. def content_security_policy_report_only(
  586. self, value: ContentSecurityPolicy | str | None
  587. ) -> None:
  588. if not value:
  589. del self.headers["content-security-policy-report-only"]
  590. elif isinstance(value, str):
  591. self.headers["Content-Security-policy-report-only"] = value
  592. else:
  593. self.headers["Content-Security-policy-report-only"] = value.to_header()
  594. # CORS
  595. @property
  596. def access_control_allow_credentials(self) -> bool:
  597. """Whether credentials can be shared by the browser to
  598. JavaScript code. As part of the preflight request it indicates
  599. whether credentials can be used on the cross origin request.
  600. """
  601. return "Access-Control-Allow-Credentials" in self.headers
  602. @access_control_allow_credentials.setter
  603. def access_control_allow_credentials(self, value: bool | None) -> None:
  604. if value is True:
  605. self.headers["Access-Control-Allow-Credentials"] = "true"
  606. else:
  607. self.headers.pop("Access-Control-Allow-Credentials", None)
  608. access_control_allow_headers = header_property(
  609. "Access-Control-Allow-Headers",
  610. load_func=parse_set_header,
  611. dump_func=dump_header,
  612. doc="Which headers can be sent with the cross origin request.",
  613. )
  614. access_control_allow_methods = header_property(
  615. "Access-Control-Allow-Methods",
  616. load_func=parse_set_header,
  617. dump_func=dump_header,
  618. doc="Which methods can be used for the cross origin request.",
  619. )
  620. access_control_allow_origin = header_property[str](
  621. "Access-Control-Allow-Origin",
  622. doc="The origin or '*' for any origin that may make cross origin requests.",
  623. )
  624. access_control_expose_headers = header_property(
  625. "Access-Control-Expose-Headers",
  626. load_func=parse_set_header,
  627. dump_func=dump_header,
  628. doc="Which headers can be shared by the browser to JavaScript code.",
  629. )
  630. access_control_max_age = header_property(
  631. "Access-Control-Max-Age",
  632. load_func=int,
  633. dump_func=str,
  634. doc="The maximum age in seconds the access control settings can be cached for.",
  635. )
  636. cross_origin_opener_policy = header_property[COOP](
  637. "Cross-Origin-Opener-Policy",
  638. load_func=lambda value: COOP(value),
  639. dump_func=lambda value: value.value,
  640. default=COOP.UNSAFE_NONE,
  641. doc="""Allows control over sharing of browsing context group with cross-origin
  642. documents. Values must be a member of the :class:`werkzeug.http.COOP` enum.""",
  643. )
  644. cross_origin_embedder_policy = header_property[COEP](
  645. "Cross-Origin-Embedder-Policy",
  646. load_func=lambda value: COEP(value),
  647. dump_func=lambda value: value.value,
  648. default=COEP.UNSAFE_NONE,
  649. doc="""Prevents a document from loading any cross-origin resources that do not
  650. explicitly grant the document permission. Values must be a member of the
  651. :class:`werkzeug.http.COEP` enum.""",
  652. )