Google Cloud Storage Backend

class cachelib.googlecloudstorage.GoogleCloudStorageCache(bucket='mybucket', client=None, key_prefix=None, default_timeout=300, delete_expired_objects_on_read=False, ignore_delete_many_errors=True, anonymous=False, check_connection=False, **kwargs)

Bases: BaseCache

Uses a Google Cloud Storage bucket as a cache backend.

Note

User-contributed functionality. This project does not guarantee that this functionality will be maintained or functional at any given time.

Note

Cache keys must meet GCS criteria for a valid object name (a sequence of Unicode characters whose UTF-8 encoding is at most 1024 bytes long).

Note

Expired cache objects are not automatically purged. If delete_expired_objects_on_read=True, they will be deleted following an attempted read (which reduces performance). Otherwise, you have to delete stale objects yourself. Consider a GCS bucket life cycle rule or other out-of-band process. For example you can use the following rule:

{
  "rule": [
    {
      "action": {"type": "Delete"},
      "condition": {"daysSinceCustomTime": 0}
    }
  ]
}

https://cloud.google.com/storage/docs/lifecycle#dayssincecustomtime

Note

bytes values are stored as is with the application/octet-stream content type. Other values are stored using serializer with the application/json content type.

Note

inc() and dec() are not atomic and reset the timeout of the key to the default. get_many() and set_many() make one request per key.

Parameters:
  • bucket (str) – Name of the bucket to use. It must already exist.

  • client (Any) – A google.cloud.storage.Client to use. If not given, one is created using anonymous and any additional keyword arguments.

  • key_prefix (str | None) – A prefix that should be added to all keys.

  • default_timeout (int | timedelta) – the default timeout that is used if no timeout is specified on set(). Either a number of seconds or a datetime.timedelta. A timeout of 0 indicates that the cache never expires.

  • delete_expired_objects_on_read (bool) – If True, if a read finds a stale object, it will be deleted before a response is returned. Will slow down responses.

  • 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.

  • anonymous (bool) – If True, create the client with anonymous credentials. Useful for testing against an emulator. The project defaults to "test" unless a project keyword argument is given.

  • check_connection (bool) – If True, the constructor will verify that the bucket exists and raise a RuntimeError if it does not or cannot be reached. If False (default), no request is made at construction and errors surface on first use.

  • kwargs (Any)

Any additional keyword arguments will be passed to google.cloud.storage.Client when client is not given.

serializer = <cachelib.serializers.GoogleCloudStorageSerializer object>
get(key)

Look up key in the cache and return the value for it.

Parameters:

key (str) – the key to be looked up.

Returns:

The value if it exists and is readable, else None.

Return type:

Any

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:

True if key has been updated, False for backend errors. Pickling errors, however, will raise a subclass of pickle.PickleError.

Return type:

bool

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 also False for already existing keys.

Return type:

bool

delete(key)

Delete key from the cache.

Parameters:

key (str) – the key to delete.

Returns:

Whether the key existed and has been deleted.

Return type:

bool

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_errors is False and a key still exists after the delete attempt.

Return type:

list[str]

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.

Parameters:

key (str) – the key to check

Return type:

bool

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:

bool