Memcached Backend¶
- class cachelib.memcached.MemcachedCache(servers=None, default_timeout=300, key_prefix=None, pool_size=1, pool_blocking=True, ignore_delete_many_errors=True, check_connection=False, memcache_client_lib=None)¶
Bases:
BaseCacheA cache that uses memcached as backend.
The first argument can either be an object that resembles the API of a
memcache.Clientor a tuple/list of server addresses. In the event that a tuple/list is passed, CacheLib tries to import the best available memcache library.This cache looks into the following packages/modules to find bindings for memcached:
pylibmcgoogle.appengine.api.memcachedmemcachelibmc
Implementation notes: This cache backend works around some limitations in memcached to simplify the interface. For example unicode keys are encoded to UTF-8 on the fly. Methods such as
get_dict()return the keys in the same format as passed. Furthermore all get methods silently ignore key errors to not cause problems when untrusted user data is passed to the get methods which is often the case in web applications. This cache doesn’t have a serializer since the underlying memcached client libraries handle serialization internally.”- Parameters:
servers (Any) – a list or tuple of server addresses or alternatively a
memcache.Clientor a compatible client.default_timeout (int | timedelta) –
the default timeout that is used if no timeout is specified on
set(). Either a number of seconds or adatetime.timedelta. A timeout of 0 indicates that the cache never expires.Changed in version 0.17.0: Accepts a
datetime.timedelta.key_prefix (str | None) – a prefix that is added before all keys. This makes it possible to use the same memcached server for different applications. Keep in mind that
clear()will also clear keys with a different prefix.pool_size (int) –
the size of the connection pool. This is only used if the memcached client library supports connection pooling.
Changelog
Added in version 0.15.0.
pool_blocking (bool) –
if the connection pool is exhausted, should the client block until a connection is available or raise an exception. This is only used if the memcached client library supports connection pooling.
Changelog
Added in version 0.15.0.
ignore_delete_many_errors (bool) –
If False, delete_many() will raise a RuntimeError if any key fails to delete. Keys that do not exist are considered successfully deleted and do not raise.
Changelog
Added in version 0.16.0.
check_connection (bool) –
If True, the constructor will verify the connection to the memcached server and raise a RuntimeError if it fails. If False (default), connection errors are ignored at construction and surface on first use.
Changelog
Added in version 0.16.1.
memcache_client_lib (Literal['pylibmc', 'google', 'memcache', 'libmc'] | None) –
Optional. A string indicating which memcache client library to use. Valid values are
pylibmc,google,memcache, andlibmc. If not provided, the library will be auto-detected based on availability.Added in version 0.17.0.
- get(key)¶
Look up key in the cache and return the value for it.
- get_dict(*keys)¶
Like
get_many()but return a dict:d = cache.get_dict("foo", "bar") foo = d["foo"] bar = d["bar"]
- add(key, value, timeout=None)¶
Works like
set()but does not overwrite the values of already existing keys.- Parameters:
key (str) – the key to set
value (Any) – the value for the key
timeout (int | timedelta | None) – the cache timeout for the key, either a number of seconds or a
datetime.timedelta(if not specified, it uses the default timeout). A timeout of 0 indicates that the cache never expires.
- Returns:
Same as
set(), but alsoFalsefor already existing keys.- Return type:
- set(key, value, timeout=None)¶
Add a new key/value to the cache (overwrites value, if key already exists in the cache).
- Parameters:
key (str) – the key to set
value (Any) – the value for the key
timeout (int | timedelta | None) – the cache timeout for the key, either a number of seconds or a
datetime.timedelta(if not specified, it uses the default timeout). A timeout of 0 indicates that the cache never expires.
- Returns:
Trueif key has been updated,Falsefor backend errors. Pickling errors, however, will raise a subclass ofpickle.PickleError.- Return type:
bool | None
- get_many(*keys)¶
Returns a list of values for the given keys. For each key an item in the list is created:
foo, bar = cache.get_many("foo", "bar")
Has the same error handling as
get().
- set_many(mapping, timeout=None)¶
Sets multiple keys and values from a mapping.
- Parameters:
- Returns:
A list containing all keys successfully set
- Return type:
- delete(key)¶
Delete
keyfrom the cache.
- delete_many(*keys)¶
Deletes multiple keys at once.
- Parameters:
keys (str) – The function accepts multiple keys as positional arguments.
- Returns:
A list containing all successfully deleted keys
- Raises:
RuntimeError – If
ignore_delete_many_errorsis False and a key still exists after the delete attempt.- Return type:
- has(key)¶
Checks if a key exists in the cache without returning it. This is a cheap operation that bypasses loading the actual data on the backend.
- clear()¶
Clears the cache. Keep in mind that not all caches support completely clearing the cache.
- Returns:
Whether the cache has been cleared.
- Return type:
- import_preferred_memcache_lib(servers, pool_size, pool_blocking=True, memcache_client_lib=None)¶
Returns an initialized memcache client. Used by the constructor.
- class cachelib.memcached.SASLMemcachedCache(servers=None, default_timeout=300, key_prefix=None, username=None, password=None, pool_size=1, pool_blocking=True, ignore_delete_many_errors=True, check_connection=False, memcache_client_lib=None, **kwargs)¶
Bases:
MemcachedCacheA
MemcachedCachethat can authenticate with SASL.Of the supported memcached client libraries only
pylibmcsupports SASL. Ifusernameorpasswordis given,pylibmcis used with the memcached binary protocol, which SASL requires. Without credentials this cache works likeMemcachedCachewith any supported library.- Parameters:
servers (Any) – a list or tuple of server addresses or alternatively a
memcache.Clientor a compatible client.default_timeout (int | timedelta) – the default timeout that is used if no timeout is specified on
set(). Either a number of seconds or adatetime.timedelta. A timeout of 0 indicates that the cache never expires.key_prefix (str | None) – a prefix that is added before all keys.
username (str | None) – the SASL username.
password (str | None) – the SASL password.
pool_size (int) – the size of the connection pool. This is only used if the memcached client library supports connection pooling.
pool_blocking (bool) – if the connection pool is exhausted, should the client block until a connection is available or raise an exception. This is only used if the memcached client library supports connection pooling.
ignore_delete_many_errors (bool) – If False, delete_many() will raise a RuntimeError if any key fails to delete. Keys that do not exist are considered successfully deleted and do not raise.
check_connection (bool) – If True, the constructor will verify the connection to the memcached server and raise a RuntimeError if it fails. If False (default), connection errors are ignored at construction and surface on first use.
memcache_client_lib (Literal['pylibmc', 'google', 'memcache', 'libmc'] | None) – Optional. A string indicating which memcache client library to use. Valid values are
pylibmc,google,memcache, andlibmc. If not provided, the library will be auto-detected based on availability, orpylibmcis used if credentials are given. AValueErroris raised if credentials are given with another library.kwargs (Any)
Any additional keyword arguments are passed to
pylibmc.Client.- import_preferred_memcache_lib(servers, pool_size, pool_blocking=True, memcache_client_lib=None)¶
Returns an initialized memcache client. Used by the constructor.
- class cachelib.memcached.SpreadSASLMemcachedCache(*args, chunksize=1048448, maxchunk=32, **kwargs)¶
Bases:
SASLMemcachedCacheA
SASLMemcachedCachethat spreads values across multiple keys so values bigger than memcached’s item size limit can be stored.Note
Spreading requires serializing the value with
serializer, which uses pickle by default and can significantly impact performance.- Parameters:
All other arguments are passed to
SASLMemcachedCache.- serializer = <cachelib.serializers.SpreadSASLMemcachedSerializer object>¶
- get(key, chunk=True)¶
Get a cached value.
- set(key, value, timeout=None, chunk=True)¶
Set a value in the cache, spreading it across multiple keys.
- Parameters:
key (str) – the key to set.
value (Any) – the value for the key.
timeout (int | timedelta | None) – the cache timeout for the key, either a number of seconds or a
datetime.timedelta.chunk (bool) – If set to
False, store the value in a single key without the serializer. This is faster, but fails for values bigger than memcached’s item size limit, and the value must be read back withget(key, chunk=False).
- Return type:
bool | None
- add(key, value, timeout=None)¶
Works like
set()but does not overwrite the values of already existing keys.- Parameters:
key (str) – the key to set
value (Any) – the value for the key
timeout (int | timedelta | None) – the cache timeout for the key, either a number of seconds or a
datetime.timedelta(if not specified, it uses the default timeout). A timeout of 0 indicates that the cache never expires.
- Returns:
Same as
set(), but alsoFalsefor already existing keys.- Return type:
- delete(key)¶
Delete
keyfrom the cache.
- has(key)¶
Checks if a key exists in the cache without returning it. This is a cheap operation that bypasses loading the actual data on the backend.
- get_dict(*keys)¶
Like
get_many()but return a dict:d = cache.get_dict("foo", "bar") foo = d["foo"] bar = d["bar"]
- set_many(mapping, timeout=None)¶
Sets multiple keys and values from a mapping.
- Parameters:
- Returns:
A list containing all keys successfully set
- Return type:
- delete_many(*keys)¶
Deletes multiple keys at once.
- Parameters:
keys (str) – The function accepts multiple keys as positional arguments.
- Returns:
A list containing all successfully deleted keys
- Raises:
RuntimeError – If
ignore_delete_many_errorsis False and a key still exists after the delete attempt.- Return type: