response.py 27 KB

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