Cache.incr()
Add delta to the number stored under key, atomically, and return the result.
Usage
Cache.incr(
key,
delta=...,
default=...,
*,
retry=False,
)Atomic across threads and processes, so concurrent increments are never lost. The entry keeps its existing expiry.
Parameters
key: Key-
The key.
delta: float = …-
The amount to add (default 1). An int or a finite float.
default: Optional[float] = …-
The starting value for a missing or expired key (default 0), an int or a finite float. Pass None to raise
KeyErrorinstead. retry: bool = False-
On a Timeout, try again until the call gets through, each round with the whole timeout, a
durable=Truehandle included. Only Timeout is retried.
Returns
int | float-
The new value. With
durable=True,default + deltaif the call failed, whatever wasstored, so a rate limiter fails open. Don’t use that number as an id: two callers can
get the same one.
Raises
KeyError-
The key is missing and
defaultis None, or withdurable=True, the call failed anddefaultis None. TypeError-
The stored value isn’t a number.
ValueError-
deltaordefaultis an infinity or a NaN. Nothing is read or written. Timeout- Another process held the write lock for longer than timeout.
Examples
cache.incr('page_views') # 1 on a missing key, then 2, 3, ...
cache.add('rate:203.0.113.7:1731', 0, expire=120) # a windowed counter: create it with an expiry,
allowed = cache.incr('rate:203.0.113.7:1731') <= 100 # then count; incr keeps the expiry