Sets an outgoing cookie name/value with the given options. Newly-set cookies are not immediately visible via `get_cookie`; they are not present until the next request. expires may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.g
(
self,
name: str,
value: Union[str, bytes],
domain: Optional[str] = None,
expires: Optional[Union[float, Tuple, datetime.datetime]] = None,
path: str = "/",
expires_days: Optional[float] = None,
**kwargs: Any
)
| 596 | return default |
| 597 | |
| 598 | def set_cookie( |
| 599 | self, |
| 600 | name: str, |
| 601 | value: Union[str, bytes], |
| 602 | domain: Optional[str] = None, |
| 603 | expires: Optional[Union[float, Tuple, datetime.datetime]] = None, |
| 604 | path: str = "/", |
| 605 | expires_days: Optional[float] = None, |
| 606 | **kwargs: Any |
| 607 | ) -> None: |
| 608 | """Sets an outgoing cookie name/value with the given options. |
| 609 | |
| 610 | Newly-set cookies are not immediately visible via `get_cookie`; |
| 611 | they are not present until the next request. |
| 612 | |
| 613 | expires may be a numeric timestamp as returned by `time.time`, |
| 614 | a time tuple as returned by `time.gmtime`, or a |
| 615 | `datetime.datetime` object. |
| 616 | |
| 617 | Additional keyword arguments are set on the cookies.Morsel |
| 618 | directly. |
| 619 | See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel |
| 620 | for available attributes. |
| 621 | """ |
| 622 | # The cookie library only accepts type str, in both python 2 and 3 |
| 623 | name = escape.native_str(name) |
| 624 | value = escape.native_str(value) |
| 625 | if re.search(r"[\x00-\x20]", name + value): |
| 626 | # Don't let us accidentally inject bad stuff |
| 627 | raise ValueError("Invalid cookie %r: %r" % (name, value)) |
| 628 | if not hasattr(self, "_new_cookie"): |
| 629 | self._new_cookie = ( |
| 630 | http.cookies.SimpleCookie() |
| 631 | ) # type: http.cookies.SimpleCookie |
| 632 | if name in self._new_cookie: |
| 633 | del self._new_cookie[name] |
| 634 | self._new_cookie[name] = value |
| 635 | morsel = self._new_cookie[name] |
| 636 | if domain: |
| 637 | morsel["domain"] = domain |
| 638 | if expires_days is not None and not expires: |
| 639 | expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days) |
| 640 | if expires: |
| 641 | morsel["expires"] = httputil.format_timestamp(expires) |
| 642 | if path: |
| 643 | morsel["path"] = path |
| 644 | for k, v in kwargs.items(): |
| 645 | if k == "max_age": |
| 646 | k = "max-age" |
| 647 | |
| 648 | # skip falsy values for httponly and secure flags because |
| 649 | # SimpleCookie sets them regardless |
| 650 | if k in ["httponly", "secure"] and not v: |
| 651 | continue |
| 652 | |
| 653 | morsel[k] = v |
| 654 | |
| 655 | def clear_cookie( |
no test coverage detected