Skip to main content

API Reference

The public API of diskcache-oxide: Cache, FanoutCache, NullCache, the CacheLike, TransactionalCacheLike and ShardedCacheLike protocols, the Caches registry, exceptions, types and serialization, memoize, the coordination recipes, and SQLite utilities.

Cache

Disk-backed cache backed by SQLite, shared safely across threads and processes.

Cache

A disk cache backed by SQLite, shared safely across threads and processes.

Cache Methods

Methods for the Cache class

Cache.directory

The directory the cache is in: the one given to the constructor, or its

Cache.timeout

Seconds a call waits for a lock or a pending fork before raising Timeout.

Cache.size_limit

The disk budget in bytes. A set() that finds the cache over it evicts entries.

Cache.cull_limit

The most entries a single set() evicts when the cache is over size_limit.

Cache.eviction_policy

'least-recently-stored' or 'none', as this handle last saw it stored (at open or its

Cache.enabled

Always True for a real cache; False for a NullCache.

Cache.set()

Store value under key, replacing any existing value.

Cache.add()

Store value only if key is missing or expired.

Cache.delete()

Remove key.

Cache.touch()

Change the expiry of an existing entry without rewriting its value.

Cache.incr()

Add delta to the number stored under key, atomically, and return the result.

Cache.decr()

Subtract delta from the number stored under key, atomically. See incr().

Cache.memoize()

Return a decorator that caches the function’s results in this cache, as diskcache’s memoize.

Cache.remove_old_formats()

Remove the caches an older diskcache-oxide format left in this cache’s directory: the

Cache.check()

Check the database and the value files against each other, as diskcache’s check().

Cache.maintenance_stats()

How background maintenance has gone on this cache in this process (see

Cache.stats()

(hits, misses) of get and cache[key] in this process, as diskcache’s stats().

Cache.durable

True for a durable=True handle.

Cache.__reversed__()

Keys in insertion order backwards, newest first (a FanoutCache: the last shard first).

Cache.expire()

Remove every expired entry, and its value file.

Cache.clear()

Remove every entry that existed when the call started.

Cache.evict()

Remove every entry tagged tag that existed when the call started.

Cache.cull()

Remove expired entries, then evict the least recently stored until under size_limit.

Cache.volume()

The cache’s size on disk in bytes: the database plus value files.

Cache.checkpoint()

Copy the write-ahead log into the database and truncate it to zero.

Cache.close()

Close this handle and return its connections.

Cache.pull()

Remove and return the item at side of a queue, as diskcache’s pull.

Cache.peek()

The item at side of a queue, without removing it, as diskcache’s peek.

Cache.peekitem()

The newest entry (or with last=False, the oldest) of any key, without removing it, as

Cache.transact()

A write transaction, for with cache.transact() as tx:.

Cache.__getitem__()

cache[key]: the value, or KeyError if it’s missing or expired, or the read failed under

Cache.__setitem__()

cache[key] = value: store a value that never expires, like set(). Under durable=True a failed write is

Cache.__delitem__()

del cache[key]: remove the entry, or raise KeyError if it’s missing or expired, or the delete failed

Cache.__contains__()

key in cache: True if the key holds a live (unexpired) value. False if the check failed under

Cache.__len__()

The number of live entries. An entry stops counting the moment it expires, whether or not

Cache.__bool__()

Always True, even when empty, so if cache: means “caching is on”.

Cache.__iter__()

Iterate over keys in insertion order. An overwrite keeps its key’s place. The walk covers

Cache.__enter__()

Return the cache, for with Cache(...) as cache:.

Cache.__exit__()

Close the cache, as close() does.

Cache.get()

Return the value stored for key, or default if it’s missing or expired.

Cache.pop()

Remove key and return its value, delivering it to exactly one caller.

Cache.reset()

Read size_limit, cull_limit or eviction_policy as stored now, or persist a new value and

Cache.iterkeys()

Iterate over keys in sorted order, optionally only those starting with prefix.

Cache.push()

Push value onto a queue and return its key, as diskcache’s push.

FanoutCache

A cache sharded over several SQLite databases, so writers in many processes stop queueing on one write lock.

FanoutCache

A disk cache split over several SQLite databases (shards), so reads and writes on different keys

FanoutCache Methods

Methods for the FanoutCache class

FanoutCache.directory

The root directory: the one given to the constructor, or its

FanoutCache.timeout

Seconds a call waits for a lock or a pending fork before raising Timeout.

FanoutCache.shards

How many shards the root has.

FanoutCache.size_limit

The disk budget in bytes: the sum of every shard’s.

FanoutCache.cull_limit

The most entries a single set() evicts from its shard when that shard is over its share.

FanoutCache.eviction_policy

Shard 0’s eviction policy, as for cull_limit.

FanoutCache.enabled

Always True for a real cache; False for a NullCache.

FanoutCache.shard_of()

The shard key lives in, from 0 to shards - 1: the same in every process and release.

FanoutCache.transact()

A write transaction on the shard key lives in, for with cache.transact(key='total') as tx:.

FanoutCache.set()

As Cache.set, on the key’s shard.

FanoutCache.add()

As Cache.add, on the key’s shard: atomic across threads and processes.

FanoutCache.delete()

As Cache.delete, on the key’s shard.

FanoutCache.touch()

As Cache.touch, on the key’s shard.

FanoutCache.incr()

As Cache.incr, on the key’s shard: atomic across threads and processes.

FanoutCache.decr()

As Cache.decr, on the key’s shard.

FanoutCache.volume()

The total disk use in bytes of every shard (databases plus value files).

FanoutCache.expire()

Remove every expired entry from every shard, and its value file, as Cache.expire does.

FanoutCache.clear()

Remove every entry that existed when the call started, from every shard.

FanoutCache.evict()

Remove every entry tagged tag that existed when the call started, from every shard, as

FanoutCache.cull()

Remove expired entries, then evict the least recently stored from each shard until it’s

FanoutCache.checkpoint()

Checkpoint every shard’s write-ahead log and truncate it to zero, as Cache.checkpoint does.

FanoutCache.memoize()

Return a decorator that caches the function’s results in this cache, as diskcache’s memoize.

FanoutCache.remove_old_formats()

As Cache.remove_old_formats(), for this cache’s root directory: an older format’s

FanoutCache.check()

Check the database and the value files against each other, as diskcache’s check().

FanoutCache.maintenance_stats()

How background maintenance has gone on this cache in this process (see

FanoutCache.stats()

(hits, misses) of get and cache[key] in this process, as diskcache’s stats().

FanoutCache.durable

True for a durable=True handle.

FanoutCache.__reversed__()

Keys in insertion order backwards, newest first (a FanoutCache: the last shard first).

FanoutCache.__iter__()

Iterate over every key once: shard 0’s in insertion order, then shard 1’s, and so on.

FanoutCache.close()

Close this handle on every shard, as Cache.close() does for one.

FanoutCache.__getitem__()

cache[key], as on Cache.

FanoutCache.__setitem__()

cache[key] = value, as on Cache.

FanoutCache.__delitem__()

del cache[key], as on Cache.

FanoutCache.__contains__()

key in cache, as on Cache.

FanoutCache.__len__()

The number of live entries in every shard: expired ones don’t count, as on Cache.

FanoutCache.__bool__()

Always True, even when empty, so if cache: means “caching is on”.

FanoutCache.__enter__()

Return the cache, for with FanoutCache(...) as cache:.

FanoutCache.__exit__()

Close the cache, as close() does.

FanoutCache.get()

As Cache.get, on the key’s shard.

FanoutCache.pop()

As Cache.pop, on the key’s shard.

FanoutCache.reset()

Read size_limit, cull_limit or eviction_policy as stored now, or persist a new value and

FanoutCache.iterkeys()

Iterate over keys in sorted order, optionally only those starting with prefix.

NullCache

Switched-off cache behaving as if every entry expires instantly.

NullCache

A switched-off cache, so app code needs no if cache is None checks.

CacheLike

What application code can rely on from a Cache, a FanoutCache or a NullCache.

TransactionalCacheLike

A CacheLike with transact() and the queue calls (push, pull, peek, peekitem), which

ShardedCacheLike

A CacheLike with a sharded cache’s transact(*, key, retry=False), which FanoutCache and

NullCache Methods

Methods for the NullCache class

NullCache.__repr__()

Shows the directory and any invalidate= cache.

NullCache.directory

The directory passed to the constructor, or None. Nothing is created there.

NullCache.timeout

The timeout passed to the constructor (default 60). Unused.

NullCache.size_limit

The size limit passed to the constructor (default 1 GiB). Unused.

NullCache.cull_limit

The cull limit passed to the constructor (default 10). Unused.

NullCache.eviction_policy

The eviction policy passed to the constructor (default ‘least-recently-stored’). Unused.

NullCache.enabled

Always False: caching is off.

NullCache.durable

Always False: a NullCache has no outages to answer.

NullCache.check()

Always []: there is nothing to check.

NullCache.remove_old_formats()

Always []: a NullCache has no directory to clean up.

NullCache.maintenance_stats()

All zero: a NullCache has nothing to maintain.

NullCache.stats()

Always (0, 0): nothing is looked up.

NullCache.reset()

Read size_limit, cull_limit or eviction_policy, or set it (checked as Cache checks it)

NullCache.get()

Return default, as every entry has already expired. With expire_time=True or tag=True,

NullCache.__getitem__()

Always raises KeyError, as every entry has already expired.

NullCache.__contains__()

Always False.

NullCache.__len__()

Always 0.

NullCache.__bool__()

Always False, so if cache: means “caching is on”.

NullCache.__iter__()

Yields nothing.

NullCache.__reversed__()

Yields nothing.

NullCache.volume()

Always 0: a NullCache uses no disk.

NullCache.checkpoint()

Always True: there is no write-ahead log to reset.

NullCache.set()

Return True without storing anything: the write succeeds, then expires instantly.

NullCache.__setitem__()

Store nothing, as set() does.

NullCache.add()

Return True without storing anything: the key is always absent, so the add succeeds.

NullCache.touch()

Always False: the key never exists.

NullCache.incr()

Return default + delta, since every count starts again from default.

NullCache.decr()

Return default - delta. See incr().

NullCache.delete()

False, or with invalidate=, delete the key from that cache and return its result.

NullCache.__delitem__()

Raise KeyError, or with invalidate=, delete the key from that cache.

NullCache.pop()

Return default, shaped as get() returns it. With invalidate=, also delete the key from

NullCache.push()

Store nothing and return the key an empty queue’s first item gets: the item expires the instant

NullCache.pull()

Return default (widened as Cache.pull widens it): the queue is always empty. Never forwarded

NullCache.peek()

Return default, as pull does.

NullCache.peekitem()

Raise KeyError: the cache is always empty.

NullCache.clear()

0, or with invalidate=, clear that cache (passing timeout on) and return its count.

NullCache.evict()

0, or with invalidate=, evict tag from that cache (passing timeout on) and return its

NullCache.memoize()

As Cache.memoize, but every call runs the function, as every entry has already expired. The

NullCache.iterkeys()

Yield nothing, or with invalidate=, that cache’s keys, so list-then-delete still works.

NullCache.transact()

A no-op context manager that yields this NullCache.

NullCache.expire()

Always 0.

NullCache.cull()

Always 0.

NullCache.close()

Do nothing. An invalidate= cache is never closed: it belongs to whoever created it.

NullCache.__enter__()

Return the cache, for with NullCache() as cache:.

NullCache.__exit__()

Do nothing, as close() does.

CacheLike Methods

Methods for the CacheLike class

CacheLike.directory

The cache directory (None for a NullCache created without one).

CacheLike.timeout

Seconds a write waits for another process’s lock before raising Timeout.

CacheLike.size_limit

The disk budget in bytes.

CacheLike.cull_limit

The most entries one set() evicts when over size_limit.

CacheLike.eviction_policy

'least-recently-stored' or 'none'.

CacheLike.enabled

True if caching is on (Cache), False if it’s off (NullCache).

CacheLike.get()

Return the value for key, or default if it’s missing or expired.

CacheLike.set()

Store value under key, with an optional expiry in seconds.

CacheLike.add()

Store value only if key is missing or expired. True if it was stored.

CacheLike.delete()

Remove key. True if a live entry was removed.

CacheLike.pop()

Remove key and return its value, or default.

CacheLike.touch()

Change an existing entry’s expiry. True if the entry existed.

CacheLike.incr()

Add delta to the number under key, atomically, and return the result.

CacheLike.decr()

Subtract delta from the number under key, atomically, and return the result.

CacheLike.durable

True for a durable=True handle (always False on a NullCache).

CacheLike.check()

Check the database and value files against each other; [] on a NullCache.

CacheLike.remove_old_formats()

Remove caches an older format left in this cache’s directory; [] on a NullCache.

CacheLike.maintenance_stats()

How background maintenance has gone on this cache in this process; all zero on a NullCache.

CacheLike.stats()

(hits, misses) of get in this process; (0, 0) on a NullCache.

CacheLike.reset()

Read or set size_limit, cull_limit or eviction_policy.

CacheLike.__reversed__()

Keys in insertion order backwards, newest first.

CacheLike.memoize()

A decorator caching a function’s results in this cache (diskcache’s memoize).

CacheLike.iterkeys()

Iterate over keys in sorted order, optionally only those starting with prefix.

CacheLike.expire()

Remove every expired entry. Returns how many were removed.

CacheLike.clear()

Remove every entry that existed when the call started. Returns how many.

CacheLike.evict()

Remove every entry tagged tag that existed when the call started. Returns how many.

CacheLike.cull()

Remove expired entries, then evict until under size_limit. Returns how many.

CacheLike.volume()

The size on disk in bytes.

CacheLike.checkpoint()

Empty the write-ahead log. True if it was reset, False if other processes kept it busy.

CacheLike.close()

Close this handle and return its connections.

CacheLike.__getitem__()

cache[key]: the value, or KeyError if it’s missing or expired.

CacheLike.__setitem__()

cache[key] = value: store a value that never expires.

CacheLike.__delitem__()

del cache[key]: remove the entry, or raise KeyError.

CacheLike.__contains__()

key in cache: True if the key holds a live value.

CacheLike.__len__()

The number of live entries: expired ones don’t count.

CacheLike.__bool__()

True if caching is on, so if cache: reads naturally.

CacheLike.__iter__()

Iterate over every key once. A Cache yields them in insertion order.

CacheLike.__enter__()

Return the cache, for use in a with block.

CacheLike.__exit__()

Close the cache.

DjangoCache

diskcache-oxide as a Django cache backend: ‘BACKEND’: ‘diskcache_oxide.DjangoCache’.

DjangoCache

A Django cache backend on a diskcache-oxide Cache (or a FanoutCache with OPTIONS['shards']).

DjangoCache Methods

Methods for the DjangoCache class

DjangoCache.cache

The Cache (or FanoutCache) under this backend, shared by every alias on its directory.

DjangoCache.make_and_validate_key()

The key as stored (prefix:version:key), checked by validate_key.

DjangoCache.validate_key()

Warn (CacheKeyWarning) about a key memcached couldn’t store, as every Django backend does.

DjangoCache.get_backend_timeout()

Seconds from now, or None for forever. Zero or less means “don’t store it”, as in Django.

DjangoCache.add()

Django’s add, plus tag=: an entry tagged here can be removed with evict(tag).

DjangoCache.get()

The value, or default on a miss (a stored None is returned as None).

DjangoCache.set()

Django’s set, plus tag=: an entry tagged here can be removed with evict(tag).

DjangoCache.touch()

Give the key a new timeout. Returns whether it was there.

DjangoCache.delete()

Delete the key. Returns whether it was there.

DjangoCache.has_key()

Whether the key is there and unexpired.

DjangoCache.incr()

Add delta atomically, across threads and processes, keeping the entry’s expiry.

DjangoCache.decr()

Subtract delta atomically, as incr adds it.

DjangoCache.get_many()

The keys that are there, with their values; a stored None is returned.

DjangoCache.set_many()

A set per key, not one transaction: a value’s pickling can run arbitrary code (load a

DjangoCache.delete_many()

Delete the keys, up to DELETE_CHUNK at a time in one transaction (one per shard on a

DjangoCache.clear()

Remove every entry in the directory: every alias, prefix and version on this LOCATION.

DjangoCache.close()

Nothing: Django calls it after every request, and the handle lives for the process.

DjangoCache.pop()

Remove the key and return its value, or default if it’s missing, atomically.

DjangoCache.evict()

Remove every entry tagged tag (with set(..., tag=) or add(..., tag=)). Returns how many.

DjangoCache.expire()

Remove expired entries now, rather than waiting for background maintenance. Returns how many.

DjangoCache.cull()

Remove expired entries, then evict until the cache is under size_limit. Returns how many.

DjangoCache.stats()

(hits, misses) since counting was enabled; see Cache.stats.

DjangoCache.maintenance_stats()

What background maintenance has done; see Cache.maintenance_stats.

DjangoCache.check()

Check the cache’s consistency, returning the problems as warnings; see Cache.check.

DjangoCache.aadd()

add, run in one sync_to_async call.

DjangoCache.aget()

get, run in one sync_to_async call.

DjangoCache.aset()

set, run in one sync_to_async call.

DjangoCache.atouch()

touch, run in one sync_to_async call.

DjangoCache.adelete()

delete, run in one sync_to_async call.

DjangoCache.ahas_key()

has_key, run in one sync_to_async call.

DjangoCache.aincr()

incr, run in one sync_to_async call.

DjangoCache.adecr()

decr, run in one sync_to_async call.

DjangoCache.aget_many()

get_many, run in one sync_to_async call.

DjangoCache.aset_many()

set_many, run in one sync_to_async call.

DjangoCache.adelete_many()

delete_many, run in one sync_to_async call.

DjangoCache.aclear()

clear, run in one sync_to_async call.

DjangoCache.aclose()

Nothing, without a thread hop: close() does nothing.

DjangoCache.open_handle()

Open this directory’s handle and share it (or a durable alias’s NullCache).

DjangoCache.serve_null()

Record a durable alias’s failed open and log it. Used by open_handle; not called directly.

Caches

A registry of named caches under one base directory.

Caches

A registry of named caches under one base directory.

CacheStats

One cache’s numbers, for an admin page. error says why it couldn’t be read, if it couldn’t.

MaintenanceStats

How background maintenance has gone on a cache in this process: maintenance_stats().

Caches Methods

Methods for the Caches class

Caches.__repr__()

Shows the base directory and the registered names.

Caches.register()

Register a cache. Nothing opens until its first lookup.

Caches.__contains__()

Whether name is registered.

Caches.__iter__()

The registered names, in registration order.

Caches.__len__()

How many caches are registered.

Caches.directory()

The directory the named cache is registered at. After a format change the cache itself

Caches.__getitem__()

The named plain cache: opened on first use, then the same object every time.

Caches.get()

The named plain cache as caches[name] returns it, or default if no cache by that name

Caches.fanout()

The named sharded cache (one registered with shards=), looked up as caches[name] is.

Caches.disable()

Later lookups of these caches return NullCache(invalidate=real).

Caches.enable()

Later lookups of these caches return the real cache again.

Caches.enabled()

Whether lookups of this cache return the real one (it may still fail to open).

Caches.stats()

Count and volume for every registered cache, opening each one. Never raises for a cache

Caches.clear()

Clear the real cache, even while it’s disabled. Returns how many entries were removed.

Caches.expire_all()

Remove expired entries from every cache. Returns how many each removed, or None for a

Caches.remove_old_formats()

Run remove_old_formats() on every registered cache, opening each one, even while it’s

Caches.close_all()

Close every opened cache and forget it; a later lookup opens it again.

Caches.__enter__()

Return the registry, for with Caches(...) as caches:.

Caches.__exit__()

Close every opened cache, as close_all() does.

Errors

Exceptions raised by cache operations.

Timeout

A lock stayed held, or a fork stayed pending, for longer than the cache’s timeout.

TransactionBusy

A thread holding one cache’s transaction couldn’t begin another’s, because another thread holds its write

UnsafeValueError

A pickle=False cache read a value that was stored with pickle.

CorruptValueError

A stored value couldn’t be decoded: an unknown mode, or bytes that don’t parse.

ForeignValueError

A stored value this build can’t read but another might: an unknown mode, tag or extension (a newer version wrote

FormatMismatchError

A database or manifest in a format this version doesn’t support, where opening the cache’s

LayoutMismatchError

The directory’s layout doesn’t match how it was opened: a plain Cache on a FanoutCache root or shard, a

ForkedInsideTransactionError

This process can’t use the cache: it’s the child of a fork that happened while a connection to

TransactionAborted

A held transaction didn’t commit and can’t: it was rolled back (after an error inside it, or by another thread

CorruptKeyError

A stored key couldn’t be read: its bytes aren’t a key this build wrote (a damaged page or file). Raised by

UnknownFileWarning

check() found a file in a cache directory that no entry names (removed with fix=True when

EmptyDirWarning

diskcache’s warning for an empty folder. Kept for code that imports it: check() never issues

Types and serialization

Storing your own types without pickle, and the key type.

register_type()

Register cls in the process-wide registry, so every cache can store it without pickle.

unregister_type()

Remove cls from the process-wide registry. Returns whether it was registered.

registered_types()

The process-wide registrations, as {name: cls}.

registry

The process-wide TypeRegistry, consulted by every cache after the one passed as types=.

TypeRegistry

Types the codecs can store without pickle: per-type encode and decode functions, or a dataclass’s

Key

A cache key: str, bytes, int (64-bit), float (not NaN), bool, None, or a tuple of those,

Memoize

The typed wrapper memoize() returns, and its sentinels.

Memoized

A function wrapped by memoize: called as the function was, plus __cache_key__.

Memoizer

What cache.memoize(...) returns: a decorator.

ENOVAL

diskcache’s “no value” sentinel. Pass it as default= to tell a miss from a stored None

UNKNOWN

diskcache’s “unknown value” sentinel, kept for code written against diskcache. A singleton that

Coordination

Locks, semaphores, throttles and other recipes that hold across every process on the machine.

Lock

A lock shared by every thread and process on the cache: acquire(), release(), locked(),

RLock

A reentrant lock shared by every thread and process on the cache: the thread holding it may

BoundedSemaphore

A semaphore shared by every thread and process on the cache: at most value holders at once.

throttle()

A decorator allowing at most count calls every seconds, across every thread and process on

barrier()

A decorator running the function under a lock made by lock_factory(cache, key, expire=...)

Averager

A running average stored under key: add(value), get(), pop().

memoize_stampede()

memoize with cache stampede protection, as diskcache’s: a result close to expiry is

SQLite and System

Information about the bundled SQLite and environment.

sqlite_version()

The SQLite version reported at runtime by sqlite3_libversion().

sqlite_compile_options()

The compile-time options of the linked SQLite (PRAGMA compile_options).

BUNDLED_SQLITE_VERSION

The SQLite version the bundled library was compiled from (the SQLITE_VERSION macro).