Cookies (Effect's Cookies): what a response's Set-Cookie headers
set, and what a Cookie request header sends.
A Cookies maps names to Cookie values and is immutable. Cookie
options are keyword arguments (CookieOptionsInput)::
cookies = empty.set_unsafe("session", "abc", path="/", http_only=True)
cookies.to_set_cookie_headers() # ["session=abc; Path=/; HttpOnly"]For client-side storage, merge_into_array and
to_request_cookie_header work on a tuple of cookies scoped by domain,
path and scheme, following RFC 6265.
Values#
| Attribute | Type | Description |
|---|---|---|
EMPTY | Cookies |
Types#
| Type | Definition | Description |
|---|---|---|
Priority | type Priority = Literal['low', 'medium', 'high'] | |
SameSite | type SameSite = Literal['lax', 'strict', 'none'] | |
CookiesErrorTag | type CookiesErrorTag = Literal['InvalidCookieName', 'InvalidCookieValue', 'InvalidCookieDomain', 'InvalidCookiePath', 'CookieInfinityMaxAge'] |
Classes#
Functions#
make_cookie#
make_cookie(name, value, **options) -> Result[Cookie, CookiesError]| Parameter | Type | Description |
|---|---|---|
name | str | |
value | str | |
options | Unpack[CookieOptionsInput] = {} |
Returns Result[Cookie, CookiesError]
def make_cookie(
name: str, value: str, **options: Unpack[CookieOptionsInput]
) -> Result[Cookie, CookiesError]:
encoded = _encode_component(value)
opts = _options(options)
error = _validate(name, encoded, opts)
if error is not None:
return Err(error)
return Ok(Cookie(name, value, encoded, opts))make_cookie_unsafe#
make_cookie_unsafe(name, value, **options) -> Cookiemake_cookie, raising the CookiesError.
| Parameter | Type | Description |
|---|---|---|
name | str | |
value | str | |
options | Unpack[CookieOptionsInput] = {} |
Returns Cookie
def make_cookie_unsafe(name: str, value: str, **options: Unpack[CookieOptionsInput]) -> Cookie:
"""``make_cookie``, raising the ``CookiesError``."""
match make_cookie(name, value, **options):
case Ok(cookie):
return cookie
case Err(error):
raise errorserialize_cookie#
serialize_cookie(cookie) -> strThe cookie as a Set-Cookie value; raises CookiesError for an
invalid one.
| Parameter | Type | Description |
|---|---|---|
cookie | Cookie |
Returns str
def serialize_cookie(cookie: Cookie) -> str:
"""The cookie as a ``Set-Cookie`` value; raises ``CookiesError`` for an
invalid one."""
error = _validate(cookie.name, cookie.value_encoded, cookie.options)
if error is not None:
raise error
out = f"{cookie.name}={cookie.value_encoded}"
options = cookie.options
if options is None:
return out
if options.max_age is not None:
out += f"; Max-Age={math.trunc(from_input_unsafe(options.max_age).to_seconds())}"
if options.domain is not None and not options.host_only:
out += f"; Domain={options.domain}"
if options.path is not None:
out += f"; Path={options.path}"
if options.priority is not None:
out += f"; Priority={options.priority.capitalize()}"
if options.expires is not None:
out += f"; Expires={format_http_date(options.expires)}"
if options.http_only:
out += "; HttpOnly"
if options.secure:
out += "; Secure"
if options.partitioned:
out += "; Partitioned"
if options.same_site is not None:
out += f"; SameSite={options.same_site.capitalize()}"
return outfrom_record#
from_record(cookies) -> Cookies| Parameter | Type | Description |
|---|---|---|
cookies | Mapping[str, Cookie] |
Returns Cookies
def from_record(cookies: Mapping[str, Cookie]) -> Cookies:
return Cookies(cookies)from_iterable#
from_iterable(cookies) -> Cookies| Parameter | Type | Description |
|---|---|---|
cookies | Iterable[Cookie] |
Returns Cookies
def from_iterable(cookies: Iterable[Cookie]) -> Cookies:
return Cookies({c.name: c for c in cookies})from_set_cookie#
from_set_cookie(headers) -> CookiesThe cookies of Set-Cookie header values; invalid ones are skipped.
| Parameter | Type | Description |
|---|---|---|
headers | Iterable[str] | str |
Returns Cookies
def from_set_cookie(headers: Iterable[str] | str) -> Cookies:
"""The cookies of ``Set-Cookie`` header values; invalid ones are skipped."""
values = [headers] if isinstance(headers, str) else headers
return from_iterable(c for c in (_parse_set_cookie(trim(h)) for h in values) if c is not None)parse_header#
parse_header(header) -> dict[str, str]A Cookie request header as names to decoded values; the first of
a repeated name wins.
| Parameter | Type | Description |
|---|---|---|
header | str |
Returns dict[str, str]
def parse_header(header: str) -> dict[str, str]:
"""A ``Cookie`` request header as names to decoded values; the first of
a repeated name wins."""
result: dict[str, str] = {}
length, pos = len(header), 0
while pos < length:
end = header.find(";", pos)
if end == -1:
end = length
eq = header.find("=", pos)
if eq == -1:
break
if eq > end:
# Skip every segment without ``=`` before ``eq`` at once (as
# jshttp/cookie does): one at a time rescans to ``eq`` for each.
pos = header.rfind(";", 0, eq) + 1
continue
key = trim(header[pos:eq])
if key not in result:
val = trim(header[eq + 1 : end])
if val.startswith('"'):
val = trim(val[1:-1])
result[key] = _decode_component(val) if "%" in val else val
pos = end + 1
return resultmerge_into_array#
merge_into_array(jar, url, cookies, now) -> tuple[Cookie, ...]jar with the cookies a response from url set, at now
(epoch milliseconds).
A cookie without Domain is host_only for the host of url; a
Domain is accepted only when that host domain-matches it (never for
an IP address or a single label such as com; there is no public
suffix list). Without Path the cookie takes the default path of
url. Max-Age wins over Expires; both become an absolute
expires. A cookie replaces the one with the same name, domain and
path in place; an expired one removes it. A plain-http url cannot set
a Secure cookie, a __Secure- or __Host- name, or one that would
replace or shadow a held Secure cookie (RFC 6265bis 5.7), as browsers
refuse them. jar is returned unchanged when url is not an absolute
URL.
| Parameter | Type | Description |
|---|---|---|
jar | Sequence[Cookie] | |
url | str | |
cookies | Cookies | |
now | float |
Returns tuple[Cookie, ...]
def merge_into_array(
jar: Sequence[Cookie], url: str, cookies: Cookies, now: float
) -> tuple[Cookie, ...]:
"""``jar`` with the cookies a response from ``url`` set, at ``now``
(epoch milliseconds).
A cookie without ``Domain`` is ``host_only`` for the host of ``url``; a
``Domain`` is accepted only when that host domain-matches it (never for
an IP address or a single label such as ``com``; there is no public
suffix list). Without ``Path`` the cookie takes the default path of
``url``. ``Max-Age`` wins over ``Expires``; both become an absolute
``expires``. A cookie replaces the one with the same name, domain and
path in place; an expired one removes it. A plain-http ``url`` cannot set
a ``Secure`` cookie, a ``__Secure-`` or ``__Host-`` name, or one that would
replace or shadow a held ``Secure`` cookie (RFC 6265bis 5.7), as browsers
refuse them. ``jar`` is returned unchanged when ``url`` is not an absolute
URL."""
parsed = _parse_url(url)
if parsed is None:
return tuple(jar)
secure_url = parsed.protocol == "https:"
stored = list(jar)
for cookie in cookies:
scoped = _scope_cookie(parsed, cookie, now)
if scoped is None:
continue
if not secure_url and _secure_only(stored, scoped):
continue
key = (scoped.name, _cookie_domain(scoped), _cookie_path(scoped))
index = next(
(
i
for i, held in enumerate(stored)
if (held.name, _cookie_domain(held), _cookie_path(held)) == key
),
None,
)
if _expired(scoped, now):
if index is not None:
del stored[index]
elif index is None:
stored.append(scoped)
else:
stored[index] = scoped
return tuple(stored)to_request_cookie_header#
to_request_cookie_header(jar, url, now) -> str | NoneThe Cookie header value for a request to url at now
(epoch milliseconds): the unexpired cookies whose domain and path match
url (Secure ones only over https), same names included, longest
path first; None when none match. A cookie without a domain is
never sent; one without a path matches every path.
| Parameter | Type | Description |
|---|---|---|
jar | Sequence[Cookie] | |
url | str | |
now | float |
Returns str | None
def to_request_cookie_header(jar: Sequence[Cookie], url: str, now: float) -> str | None:
"""The ``Cookie`` header value for a request to ``url`` at ``now``
(epoch milliseconds): the unexpired cookies whose domain and path match
``url`` (``Secure`` ones only over https), same names included, longest
path first; ``None`` when none match. A cookie without a ``domain`` is
never sent; one without a ``path`` matches every path."""
parsed = _parse_url(url)
if parsed is None:
return None
host = parsed.hostname
secure = parsed.protocol == "https:"
def matches(cookie: Cookie) -> bool:
domain = _cookie_domain(cookie)
options = cookie.options or _NO_OPTIONS
return (
domain is not None
and (host == domain if options.host_only else _domain_matches(host, domain))
and _path_matches(parsed.pathname, _cookie_path(cookie))
and not _expired(cookie, now)
and (secure or not options.secure)
)
matching = sorted(
(cookie for cookie in jar if matches(cookie)), key=lambda c: -len(_cookie_path(c))
)
if not matching:
return None
return "; ".join(f"{c.name}={c.value_encoded}" for c in matching)