xtr_http_foundation ¶
The request surface an incoming HTTP request is matched and measured against.
A matcher answers one question about a request that arrived — its method, path, host, port, scheme, a header, a query parameter, an attribute, the address it came from, whether its body is JSON, or whatever a callable reads of it — and a chain of them answers the whole of it, so what a piece of code claims is a value it can be handed rather than a condition written into it.
Beside them are the address helpers those questions are built on: whether an IP falls inside a network, and whether it is one only this network can reach.
A request is also measured: a request rate limiter counts it under the limits its own content names — the account it carries, the address it came from — and answers with the strictest of them, without this library prescribing where the count is kept. And a response is helped along too, with the header value that sets a cookie on the client, or clears one.
A request can also be stateful: a session carries attributes under an ID cookie, kept in whatever storage the application points at.
ChainRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request only when every matcher it chains claims it.
What a piece of code will look at is usually more than one thing — a
POST, carrying JSON, from inside this network — and this is how those
are said together without any matcher learning about the others.
A chain of nothing claims every request: nothing constrains it, so there is nothing for it to refuse.
Record the matchers that must all claim a request.
Parameters:
-
matchers(Iterable[RequestMatcherInterface]) –The matchers to chain. Read once and kept, so a chain built over a generator answers the same on every request, and a sequence the caller goes on to change cannot alter what the chain claims.
matches
async
¶
Tell whether every chained matcher claims request.
The first refusal is the answer, so a matcher that reads the body is never asked for a request an earlier one already turned away.
IpUtils ¶
Where an address sits: in a network, in a private one, or hidden by its last bytes.
A namespace rather than something to build — every answer here is a function of its arguments. Text that is not an address is no error for the checks: they answer about a request from a stranger, whose address is theirs to misspell, and an address nobody can read is one no network holds.
check_ip
staticmethod
¶
Whether request_ip falls in any of ips.
Parameters:
-
request_ip(str) –the address to place, written as IPv4 or IPv6.
-
ips(str | Sequence[str]) –a network in CIDR notation, a single address, or several of either.
Returns:
-
bool–Whether any of them holds the address;
Falsefor text that is no address.
check_ip4
staticmethod
¶
Whether request_ip falls in the IPv4 network or address ip.
Parameters:
-
request_ip(str) –the address to place, written as IPv4.
-
ip(str) –a network in CIDR notation, or a single address, which stands for itself.
Returns:
-
bool–Whether the network holds the address;
Falsewhen either is no IPv4 one.
check_ip6
staticmethod
¶
Whether request_ip falls in the IPv6 network or address ip.
Parameters:
-
request_ip(str) –the address to place, written as IPv6.
-
ip(str) –a network in CIDR notation, or a single address, which stands for itself.
Returns:
-
bool–Whether the network holds the address;
Falsewhen either is no IPv6 one.
anonymize
staticmethod
¶
ip with its last bytes zeroed, so what is left no longer names one machine.
Parameters:
-
ip(str) –the address to hide, bracketed or carrying a zone if that is how it came.
-
v4_bytes(int, default:1) –how many of an IPv4 address's four bytes to drop.
-
v6_bytes(int, default:8) –how many of an IPv6 address's sixteen bytes to drop.
Returns:
-
str–The address written as it arrived: bracketed if it was, and dotted where it
-
str–carries an IPv4 one. A zone is never given back — it names an interface, which
-
str–is as much a trace of who was asked as the bytes just dropped.
Raises:
-
InvalidArgumentError–when asked for fewer than no bytes, for more than the address has, or for text that is no address at all.
is_private_ip
staticmethod
¶
Whether ip is an address only this network can reach.
Parameters:
-
ip(str) –the address to place, written as IPv4 or IPv6.
Returns:
-
bool–Whether it falls in any of :attr:
PRIVATE_SUBNETS.
Raises:
-
InvalidArgumentError–when
ipis not an address written plainly. This one refuses where the checks above answer, because its caller is asking whether an address may be reached out to, and text nobody can read is not an address that failed the question — it is a question nobody can answer.
AbstractRequestRateLimiter ¶
Bases: PeekableRequestRateLimiterInterface, ABC
Counts a request under every limiter a subclass names for it.
A request usually counts under more than one limit at once — the account it names and the address it came from — and the answer that matters is the strictest of them, because a request passes only when every limit passes. This holds the counting, the looking ahead and the forgetting, so a subclass says only which limiters a request counts under.
A request that counts under no limiter at all is unlimited: nothing constrains it, so there is nothing to refuse.
consume
async
¶
Count request once against every limit it counts under.
peek
async
¶
Report every limit request counts under, without counting it.
reset
async
¶
Forget every hit counted for the keys request counts under.
get_limiters
abstractmethod
¶
Return the limiters request counts under.
The keys a request counts under are read here — the address it came from, the account it names — because that is the one thing this shape cannot know. Called once per consumption and once per reset.
Parameters:
-
request(ServerRequestInterface) –The request that arrived.
Returns:
-
Sequence[RateLimiterInterface]–The limiters to count under; none for a request that is
-
Sequence[RateLimiterInterface]–unlimited.
PeekableRequestRateLimiterInterface ¶
Bases: RequestRateLimiterInterface, Protocol
A request limiter that reports its limit without counting against it.
Worth its own member where most requests will pass and only the failures should count — a login form, where the attempt is counted only when it fails. Looking ahead answers from the one place the count lives, and counting only on the failure keeps it that way, where consuming on every request and undoing the count on success would go there twice.
peek
async
¶
Report the limit request counts under, without counting it.
Parameters:
-
request(ServerRequestInterface) –The request that arrived.
Returns:
-
RequestRateLimitInterface–The state of the limit as it stands, this request not counted.
RateLimiterInterface ¶
Bases: Protocol
Counts the hits of one key — one user, one address, one account — against a limit.
A request limiter reads the keys it cares about out of the request and hands each of them one of these, so this is the least it asks of a counter: spend tokens, and forget the hits counted. A counter that can do more — book tokens for a moment that lies ahead, say — serves as well, since a counter with more members still answers this shape.
Spending zero tokens changes nothing and reports the limit as it stands, which is how a request limiter looks ahead without spending anything.
consume
async
¶
Spend tokens now if they are available; spend nothing otherwise.
Awaited because the count lives where the hits were counted — a store shared by every server counting them.
Parameters:
-
tokens(int, default:1) –How many tokens to spend; zero to only report the limit as it stands.
Returns:
-
RequestRateLimitInterface–The state of the limit as the spending left it.
RequestRateLimiterInterface ¶
Bases: Protocol
Limits requests by what they are and who sent them, not by one key handed to it.
A plain limiter counts the hits of a key it is given; a request limiter reads the request and decides what to count — the address it came from, the account it names, both at once — so the rule about which requests share a limit is a value the caller configures rather than a key the caller computes. That is also why it is awaited: the count lives where the hits were counted, a store shared by every server counting them.
consume
async
¶
Count request against its limit.
Parameters:
-
request(ServerRequestInterface) –The request that arrived.
Returns:
-
RequestRateLimitInterface–The state of the limit as counting this request left it.
reset
async
¶
Forget every hit counted for the keys this request counts under.
RequestRateLimitInterface ¶
Bases: Protocol
The state of a limit over requests, as one consumption left it.
A request limiter does not keep the count itself — it reads the limiters it is built from, and answers with the state the strictest of them was left in. This is the shape it reads that state through, so a limiter answers in its own result type rather than one this library prescribes: whatever carries these members serves, and the members are named as the counting packages name them, so theirs do.
Two instants are told apart. :attr:retry_after is when the tokens this
caller asked for become available; :attr:reset_at is when the limiter
is back to holding every token — None for a limit that has no such
moment.
reset_at
property
¶
When the limiter holds every token again; None when it has no such moment.
AttributesRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request whose attributes all match the expressions named for them.
An attribute is what handling the request worked out about it — the named parameters a path matched, the user an authorization header resolved to — so this matcher is how a rule is written about a finding rather than about the request as it arrived.
An attribute that is not text is never claimed: there is nothing to match an expression against, and neither is one the request does not carry at all.
Record one expression per attribute, all of which must match.
Parameters:
-
regexps(Mapping[str, str]) –Each attribute name mapped to the expression its value has to match. Read when the matcher is built.
Raises:
-
InvalidArgumentError–When one of the expressions does not read as one; it names the expression.
matches
async
¶
Tell whether every named attribute of request matches its expression.
CallableRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request when a callable says so.
The escape hatch when no matcher here expresses the claim — the callable reads the request on its own, and the request's attributes carry what a handler derived of it, a route's path parameters among them. The callable answers as it is called, so it decides from what the request already carries; a claim that has to be awaited is better written as a matcher of its own.
Record the callable that decides the claim.
Parameters:
-
decide(Callable[[ServerRequestInterface], bool]) –Reads the request and tells whether it is claimed. Called once per question, so it should decide rather than gather.
matches
async
¶
Tell whether the callable claims request.
HeaderRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request carrying every header named, whatever each one says.
Only their presence is asked about: this is the rule for "a request a gateway of ours has been through", where the header that proves it is there or is not, and what it holds is somebody else's business.
Names are matched the way HTTP matches them, without regard to case. A matcher naming no header at all claims every request: it constrains nothing.
Record the header names a request has to carry.
Parameters:
-
headers(Sequence[str] | str) –One name or several; any of them may hold a comma-separated list of names.
matches
async
¶
Tell whether request carries every header this matcher names.
HostRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request whose host matches an expression.
The expression is searched for in the host rather than having to describe
the whole of it, so \.example\.com$ is the rule for a subdomain and
^admin\.example\.com$ the rule for exactly one host.
A host names the same machine however it is written, so it is matched without regard to case.
Record the expression a request's host has to match.
Parameters:
-
regexp(str) –The expression, read when the matcher is built.
Raises:
-
InvalidArgumentError–When it does not read as one; it names the expression.
matches
async
¶
Tell whether the host of request matches this matcher's expression.
IpsRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request that came from one of the addresses or networks named.
The address is the one the server accepted the connection from, so a request that travelled through a proxy comes from the proxy: a rule about the original caller belongs where the forwarded headers are trusted and resolved.
A matcher naming no address at all claims every request: it constrains nothing.
Record the addresses and networks a request may come from.
Parameters:
-
ips(Sequence[str] | str) –A single address, a network in CIDR notation such as
192.168.1.0/24, or several of either; any of them may hold a comma-separated list.
matches
async
¶
Tell whether request came from any of the addresses this matcher names.
IsJsonRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request whose body reads as JSON.
The body itself is read, not the Content-Type header: a sender that
announces nothing still sent JSON, and one that announces JSON and sent
something else did not. Any JSON value counts — an object, an array, a
number, a string — so this is the rule for "a body worth decoding" rather
than for a shape.
A body nobody can read is not claimed, and neither is one that is not even text, nor one nested deeper than the parser goes: each is the same answer as a body that is not JSON, since none can be decoded.
matches
async
¶
Tell whether the body of request reads as JSON.
The whole body is read, from its first byte: a stream another matcher has already read is rewound first, so the order matchers are chained in changes nothing.
MethodRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request whose method is one of those named.
The names are read in upper case, since that is the case every method is
registered under, so a matcher may be configured in whichever case reads
best. The request's own method is compared as it arrived: a method is
case-sensitive on the wire, and get is not GET.
A matcher naming no method at all claims every request: it constrains nothing.
Record the methods a request may use.
Parameters:
-
methods(Sequence[str] | str) –One method or several; any of them may hold a comma-separated list of methods.
matches
async
¶
Tell whether the method of request is one this matcher names.
PathRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request whose path matches an expression.
The expression is searched for in the path rather than having to describe
the whole of it, so /admin is the rule for anything under that path and
^/admin/[0-9]+$ the rule for exactly one shape of it. Nothing in the
expression is a path parameter: ^/{_locale}/login$ matches a path
holding those very braces, not one holding a language.
A newline in a path matches ., since a path is one value rather than
several lines — so an expression bounded by ^ and $ cannot be
slipped past with an escaped control character.
Record the expression a request's path has to match.
Parameters:
-
regexp(str) –The expression, read when the matcher is built.
Raises:
-
InvalidArgumentError–When it does not read as one; it names the expression.
matches
async
¶
Tell whether the path of request matches this matcher's expression.
PortRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request asked of one port.
This is the rule for an application answering on more than one port — a public one and an administrative one — where which of them a request arrived on is the whole of what separates them.
Record the port a request has to have been asked of.
Parameters:
-
port(int) –The port.
matches
async
¶
Tell whether request was asked of this matcher's port.
QueryParameterRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request whose query string opens with the parameters named.
Only their presence is asked about, never their values: this is the rule for "a request asking the question this code answers", where a parameter being there is what says so.
They are matched by position, and the first of them has to be the query's first parameter: a query carrying further parameters after them is claimed, while one missing any of them, or carrying them in another order, is not. The names are read in lower case, and the query's own are compared as they arrived — a query string is a value, and nothing says a parameter means the same written in another case.
A matcher naming no parameter at all claims every request: it constrains nothing.
Record the query parameters a request has to open with.
Parameters:
-
parameters(Sequence[str] | str) –One name or several; any of them may hold a comma-separated list of names.
matches
async
¶
Tell whether the query of request opens with the parameters named.
SchemeRequestMatcher ¶
Bases: RequestMatcherInterface
Claims a request made over one of the schemes named.
This is the rule for "only over a connection nobody can read" —
SchemeRequestMatcher("https") — which is how a firewall says that a
credential must never travel in the clear.
The names are read in lower case, as a scheme is matched.
A matcher naming no scheme at all claims every request: it constrains nothing.
Record the schemes a request may be made over.
Parameters:
-
schemes(Sequence[str] | str) –One scheme or several; any of them may hold a comma-separated list of schemes.
matches
async
¶
Tell whether the scheme of request is one this matcher names.
RequestMatcherInterface ¶
Bases: Protocol
Decides whether the rule a matcher stands for holds for a request.
One matcher constrains one thing — the method, the path, the address it came from — so what a firewall, an endpoint or a limiter claims is a value it can be handed rather than a condition written into it, and a chain of them says the whole of it.
matches
async
¶
Tell whether this matcher claims request.
Awaited because a rule may be about the body, which arrives as it is read. A matcher that only reads the head of the request still answers this way, so one can be swapped for another.
Parameters:
-
request(ServerRequestInterface) –The request that arrived.
Returns:
-
bool–Truewhen the request is one this matcher claims.
Session ¶
Session(storage: SessionStorageInterface, *, cookie: SessionCookieConfig = _DEFAULT_COOKIE, cookie_value: str | None = None, clock: ClockInterface | None = None)
Bases: SessionInterface
The attributes a stateful request carries, under an ID the cookie reattaches.
A session is a mapping of names to values and an ID; the mapping lives in memory for the request and in the storage between requests, and the ID is how the two are told apart. The cookie carries the ID to the client and back, and nothing else — the values never leave the server.
Nothing is read from the storage until the first attribute is asked for, so a request that never touches its session costs nothing; and a session on the memory storage performs no I/O at all, ever.
Only an ID the storage knows is reattached: one it holds nothing under is replaced by a fresh one when the session starts, so a caller cannot choose the ID a session is stored under. A session is written back only when its attributes differ from what it loaded, or its ID is new; and a reattached one only over an entry still stored, so a request that read the session before a logout deleted it cannot bring it back.
Record where the attributes are kept, and decide the ID.
Parameters:
-
storage(SessionStorageInterface) –Where the attributes are kept between requests.
-
cookie(SessionCookieConfig, default:_DEFAULT_COOKIE) –The shape of the cookie that carries the ID.
-
cookie_value(str | None, default:None) –The ID cookie the request carried, as the request read it. One that is no readable ID — misspelled, upper case, somebody else's format — is treated as no cookie at all: the stranger's cookie is theirs to misspell, so a new ID is made and nothing is ever stored under the unreadable one.
-
clock(ClockInterface | None, default:None) –The reader of the current instant, for dating the cookie's expiry.
from_request
classmethod
¶
from_request(request: ServerRequestInterface, storage: SessionStorageInterface, *, cookie: SessionCookieConfig = _DEFAULT_COOKIE) -> Self
Build the session a request reattaches, reading the ID cookie it carried.
The one request-to-session path: the wiring, the firewall glue and the tests all come through here, because the cookie the request carried is the request's business to read.
Parameters:
-
request(ServerRequestInterface) –The request that arrived.
-
storage(SessionStorageInterface) –Where the attributes are kept between requests.
-
cookie(SessionCookieConfig, default:_DEFAULT_COOKIE) –The shape of the cookie that carries the ID; its name is the name read from the request. A
secureleft unset is settled here, by the request's scheme.
Returns:
start
async
¶
Load the attributes the storage holds under the ID.
Every member that touches the attributes starts the session first, so a caller rarely needs this one; it is the way to pay for the session up front, before a response is half-written.
A reattached ID the storage holds nothing under is replaced here by
a fresh one, whose cookie is then staged. Tasks of one request may
start the session at once; the storage is read once, by the first,
and the others wait for it — a second read landing after a set
would overwrite what was set. A started session returns before the
lock, so the members that start it on every call never queue behind
another task.
Raises:
-
SessionError–When the storage fails to load the session.
get
async
¶
Return the attribute under name, or default when there is none.
set
async
¶
Set the attribute under name to value, as it was given.
What the value must be to survive the storage is the storage's own
contract, and it is heard at save().
remove
async
¶
Drop the attribute under name, returning the value it had.
Returning what was removed saves a caller that wants the value — an error message shown once, a path redirected to — from reading it first and dropping it after.
clear
async
¶
Drop every attribute, in memory; the stored entry follows at save().
Starting first means the attributes still stored are loaded and
dropped with the rest, so a session cleared and saved leaves
nothing stored either — save() of an empty session deletes the
entry.
migrate
async
¶
Carry the attributes to a new ID, keeping every one of them.
The session is started first, so the attributes still stored under
the old ID travel with it. The old entry is deleted only when
destroy_old says so — a session that may still be open in
another request keeps its entry until the one rotating the ID
decides the old one is dead.
Parameters:
-
destroy_old(bool, default:False) –Whether to delete the entry stored under the old ID.
invalidate
async
¶
Empty the session and carry what is left — nothing — to a new ID.
The attributes are dropped and the entry under the old ID deleted, so nothing of the session survives but the session itself; the cookie is issued again under the new ID, never taken away.
save
async
¶
Write the attributes through the storage.
A session that was never started is left alone — there is nothing to write and no entry to make — so the listener that saves every response needs no condition of its own. A session that holds no attribute deletes the entry rather than writing an empty one: a request that only consumed its session leaves none behind.
A reattached session whose attributes equal what it loaded writes nothing, so a request that only read cannot overwrite another's write; one that changed writes only over an entry still stored, and a session deleted meanwhile stays deleted.
The entry is written to live as long as the cookie config's
lifetime names, the application's notion of how long a session
lives; a lifetime of None — the browser session, which
names no moment to expire at — leaves the span to the storage's
own default.
Raises:
-
SessionError–When the storage fails to write or to delete.
-
InvalidArgumentError–When the storage keeps values in a format an attribute cannot round-trip — the cache-pool storage refuses one here, at the boundary, rather than losing it quietly.
staged_set_cookie ¶
Return the Set-Cookie value that carries the ID, when it must be sent.
The cookie is staged when the ID was made for this request — no
readable one arrived — or was changed by migrate() or
invalidate(); a request that reattached the ID it was given
sends nothing, so the client is not told a cookie it already has.
The value is never the cleared form: invalidate() re-issues
under the new ID, and nothing in this library takes a session
cookie away.
Returns:
SessionCookieConfig
dataclass
¶
SessionCookieConfig(name: str = 'xtr_session', path: str | None = '/', domain: str | None = None, secure: bool | None = None, httponly: bool = True, samesite: str | None = 'lax', lifetime: int | None = None)
The cookie a session's ID travels in, as the response writes it.
The shape is configuration, validated once where it is built, so a
cookie no browser would keep is refused at wiring time rather than at
the first response. The lifetime is the application's notion of how
long a session lives: the cookie is dated by it, and the storage entry
is written to live as long — a lifetime of None is the browser
session, which names no moment to expire at, and the storage falls
back to the lifetime it is configured with.
What cannot sit in a Set-Cookie attribute at all — a path or a
domain carrying the separators of the attributes that follow — is
refused by the header builder the cookie is written through, which
owns those rules once for every cookie it builds.
Attributes:
-
name(str) –The cookie's name.
-
path(str | None) –The path the cookie is available under; the whole site by default.
-
domain(str | None) –The domain the cookie is available to; every host that reads it when
None. -
secure(bool | None) –Whether the cookie travels only over a secure connection;
None, the default, makes itSecureexactly when the request it answers came over https. Behind a proxy that ends TLS, the scheme is https only where the server reads the proxy's forwarded headers. -
httponly(bool) –Whether the cookie stays out of the scripts a page runs.
-
samesite(str | None) –Whether the cookie travels on cross-site requests —
"lax","strict"or"none", read without regard to case;Noneor""writes no attribute. -
lifetime(int | None) –How many seconds the session lives, or
Nonefor one that expires with the browser session.
SessionInterface ¶
Bases: Protocol
The attributes a stateful request carries, under an ID the cookie reattaches.
Every member that can reach the storage is awaited — one storage must be swappable for another, and a remote one is awaited — exactly as every matcher is awaited even when it only reads the head of a request. The three that cannot reach it answer from memory alone.
The first member that touches the attributes starts the session, so a
request that never asks for its session never loads one, and save()
on a session that was never started does nothing, so the listener that
saves every response needs no condition of its own.
start
async
¶
Load the attributes the storage holds under the ID.
Idempotent. The first member that touches the attributes starts the session, so a caller rarely needs this one; it is the way to pay for the session up front, before a response is half-written.
Raises:
-
SessionError–When the storage fails to load the session.
get
async
¶
Return the attribute under name, or default when there is none.
Starts the session when it was not started.
set
async
¶
Set the attribute under name to value.
Starts the session when it was not started. The value is kept as it
was given; what it must be to survive the storage is the storage's
own contract, and it is heard at save().
has
async
¶
Tell whether the session carries an attribute under name.
Starts the session when it was not started.
remove
async
¶
Drop the attribute under name, returning the value it had.
Returning what was removed saves a caller that wants the value — an error message shown once, a path redirected to — from reading it first and dropping it after. Starts the session when it was not started.
clear
async
¶
Drop every attribute the session carries.
The stored entry follows at save(), which deletes it rather
than writing an empty one. Starts the session when it was not
started, so the attributes still stored are dropped with the rest.
migrate
async
¶
Carry the attributes to a new ID, keeping every one of them.
The old entry is deleted only when destroy_old says so — a
session that may still be open in another request keeps its entry
until the one rotating the ID decides the old one is dead. Starts
the session when it was not started, so what is stored under the
old ID travels with it.
Parameters:
-
destroy_old(bool, default:False) –Whether to delete the entry stored under the old ID.
invalidate
async
¶
Empty the session and carry what is left — nothing — to a new ID.
The attributes are dropped and the entry under the old ID deleted, so nothing of the session survives but the session itself; the cookie is issued again under the new ID.
save
async
¶
Write the attributes through the storage.
A session that was never started is left alone — there is nothing to write and no entry to make — and one that holds no attribute deletes the stored entry rather than writing an empty one.
Raises:
-
SessionError–When the storage fails to write or to delete.
-
InvalidArgumentError–When the storage keeps values in a format an attribute cannot round-trip — the cache-pool storage refuses one here, at the boundary, rather than losing it quietly.
staged_set_cookie ¶
Return the Set-Cookie value that carries the ID, when it must be sent.
The cookie is staged when the ID was made for this request — no
readable one arrived — or was changed by migrate() or
invalidate(); a request that reattached the ID it was given
sends nothing, so the client is not told a cookie it already has.
Returns:
MemorySessionStorage ¶
Bases: SessionStorageInterface
Keeps the sessions of one process, for as long as the process lives.
The zero-configuration storage and the test default: no entry survives
a restart and no two servers share one, so an application that needs
either points the session at a storage of its own. The ttl a write
names is not counted — counting it would need a clock, and the entries
live exactly as long as the process anyway.
Entries are kept as the JSON the cache-pool storage writes, so a value that storage refuses is refused here too, and what a reader gets is a copy of its own: changing it reaches no other request.
Keep no session yet.
SessionStorageInterface ¶
Bases: Protocol
A persistence port: the attributes in, the attributes out, the entry gone.
The session owns the attributes, the ID and the rotation; the storage persists them, nothing more. Every member is awaited, because one storage must be swappable for another and a remote one is awaited.
The rules:
readanswersNonefor an ID that holds nothing — an entry the backend expired counts as nothing, exactly as one that never was.deleteof an ID that holds nothing is fine, not an error.- What a value must be to survive the round trip is the storage's own
contract, and it is heard at
write— loudly, never a silent loss. writewithmust_existwrites only over an entry still there: a session another request deleted — a logout — is not brought back by a request that read it before.
read
async
¶
Return the attributes stored under session_id, or None when it holds nothing.
Parameters:
-
session_id(str) –The ID whose attributes are asked for.
Returns:
write
async
¶
write(session_id: str, data: Mapping[str, object], ttl: float | None, *, must_exist: bool = False) -> bool
Store data under session_id, the whole of it, to live ttl seconds.
A ttl of None names no moment to expire at: the entry
lives as long as the storage is configured to keep it.
Parameters:
-
session_id(str) –The ID to store the attributes under.
-
data(Mapping[str, object]) –The attributes, all of them at once.
-
ttl(float | None) –How many seconds the entry is to live, or
Nonefor the storage's own default. -
must_exist(bool, default:False) –Write only when an entry is already stored under
session_id.
Returns:
-
bool–Falsewhenmust_existis set and the entry is gone, so -
bool–nothing was written;
Trueonce the entry is kept.
Raises:
-
InvalidArgumentError–When a value in
datacannot round-trip through the storage's format. -
SessionError–When the storage fails to keep the entry.
delete
async
¶
Remove the entry under session_id; an ID holding nothing is fine.
Raises:
-
SessionError–When the storage fails to remove the entry.
cleared_cookie_header_value ¶
cleared_cookie_header_value(name: str, *, path: str | None = '/', domain: str | None = None, secure: bool = False, httponly: bool = True, samesite: str | None = 'lax') -> str
Return the value a Set-Cookie header carries to clear one cookie.
A browser drops a cookie when the header that names it dates it behind now, so clearing is setting with the value emptied — and the path and the domain must be the ones the cookie was set with, because a browser tells cookies apart by all three.
Parameters:
-
name(str) –The cookie's name, as it was set.
-
path(str | None, default:'/') –The path the cookie was set under.
-
domain(str | None, default:None) –The domain the cookie was set to.
-
secure(bool, default:False) –Whether the cookie was set to travel only over a secure connection.
-
httponly(bool, default:True) –Whether the cookie was kept out of the scripts a page runs.
-
samesite(str | None, default:'lax') –The cross-site rule the cookie was set with.
Returns:
-
str–The header value, ready for
with_header("Set-Cookie", ...).
cookie_header_value ¶
cookie_header_value(name: str, value: str, *, expires: datetime | None = None, path: str | None = '/', domain: str | None = None, secure: bool = False, httponly: bool = True, samesite: str | None = 'lax') -> str
Return the value a Set-Cookie header carries to set one cookie.
A response sets a cookie by carrying this value, so the cookie is built where the response is, in the header it already knows how to place, and no response type of this library's own is dragged in for it.
The value is per cent-encoded as it cannot sit in a header — a space, a slash, anything a separator could read as — and so is a name carrying the characters that give a cookie its shape. A value that is empty writes the cleared form instead: a browser keeps a cookie only while it is dated ahead, so the cookie is dated a year behind and ages out at once.
Parameters:
-
name(str) –The cookie's name.
-
value(str) –The cookie's value; empty to clear the cookie.
-
expires(datetime | None, default:None) –When the cookie stops being kept. Written as both the
expiresa person reads and theMax-Agea client counts down, since a client honours only one of them and which one differs. A naive datetime is read as UTC.Nonefor a cookie that lives for the session. -
path(str | None, default:'/') –The path the cookie is available under; the whole site by default, and an empty path is read the same way.
-
domain(str | None, default:None) –The domain the cookie is available to; every host that reads it when
None. -
secure(bool, default:False) –Whether the cookie travels only over a secure connection.
-
httponly(bool, default:True) –Whether the cookie stays out of the scripts a page runs.
-
samesite(str | None, default:'lax') –Whether the cookie travels on cross-site requests —
"lax","strict"or"none", read without regard to case;Noneor""writes no attribute.
Returns:
-
str–The header value, ready for
with_header("Set-Cookie", ...).
Raises:
-
InvalidArgumentError–When the name is empty or carries a reserved prefix without what the prefix asks for, when
samesiteis none of the three, or when the path or the domain carries the separators of the attributes that follow.