You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If would be great if this backend could be added to the list.
Here is an attempt:
importdatetimeimportzlibfromtypingimportAnyimportboto3importmsgspecfromaiocache.baseimportBaseCachefromaiocache.serializersimportBaseSerializerfromaiocache.serializers.serializersimport_NOT_SETfromboto3.dynamodb.typesimportBinaryclassMsgSpecSerializer(BaseSerializer):
"""Transform data to bytes using msgspec.dumps and msgspec.loads to retrieve it back. You need to have ``msgspec`` installed in order to be able to use this serializer. :param encoding: str. Can be used to change encoding param for ``msg.loads`` method. Default is utf-8. :param use_list: bool. Can be used to change use_list param for ``msgspec.loads`` method. Default is True. """def__init__(self, encoding=_NOT_SET, use_list=True, compress=False):
ifnotmsgspec:
raiseRuntimeError("msgspec not installed, MsgSpecSerializer unavailable")
self.encoding=self.DEFAULT_ENCODINGifencodingis_NOT_SETelseencodingself.use_list=use_listself.compress=compressdefdumps(self, value) ->bytes:
"""Serialize the received value using ``msgpack.dumps``. :param value: obj :returns: bytes """output=msgspec.msgpack.encode(value)
ifself.compress:
output=zlib.compress(output)
returnoutputdefloads(self, value: bytes) ->Any:
"""Deserialize value using ``msgpack.loads``. :param value: bytes :returns: obj """ifvalueisNone:
returnNoneifisinstance(value, Binary):
value=value.valueifisinstance(value, memoryview):
value=bytes(value)
decoded=msgspec.msgpack.decode(value)
ifself.compress:
decoded=zlib.decompress(decoded)
returndecodedclassDynamoDBBackend(BaseCache):
def__init__(self, table_name="cache_table", region_name="us-east-1", key_column="CacheKey", val_column="CacheValue", ttl_attribute_name="CacheTTL", **kwargs):
super().__init__(**kwargs)
self.key_column=key_columnself.val_column=val_columnself.ttl_attribute_name=ttl_attribute_nameself.table_name=table_nameself.region_name=region_nameself.resource=boto3.resource("dynamodb", region_name=region_name)
self.table=self.resource.Table(table_name)
asyncdef_get(self, key, encoding="utf-8", _conn=None):
response=self.table.get_item(Key={self.key_column: key})
item=response.get("Item")
ifnotitem:
returnNonevalue=item[self.val_column]
returnself.serializer.loads(value)
asyncdef_set(self, key, value, ttl=0, _cas_token=None, _conn=None):
serialized_value=self.serializer.dumps(value)
item= {self.key_column: key, self.val_column: serialized_value}
ifttl>0:
expires_at=datetime.datetime.now() +datetime.timedelta(seconds=ttl)
item[self.ttl_attribute_name] =int(expires_at.timestamp())
self.table.put_item(Item=item)
returnTrueasyncdef_delete(self, key, _conn=None):
self.table.delete_item(Key={self.key_column: key})
returnTrueasyncdef_exists(self, key, _conn=None):
# Assume a keys exists as dynamodb does not have a direct way to check if a key existsreturnTrueasyncdef_clear(self, namespace=None, _conn=None):
raiseNotImplementedError("Clearing all items is not supported for DynamoDB.")
asyncdef_close(self, *args, _conn=None, **kwargs):
pass# No specific close logic required for boto3defbuild_key(self, key: str, namespace: str|None=None) ->str:
returnself._str_build_key(key, namespace)
classDynamoDBCache(DynamoDBBackend):
"""DynamoDB cache implementation. With the following components as defaults: - serializer: :class:`BaseSerializer` - plugins: [] Config options are: :param serializer: obj derived from :class:`aiocache.serializers.BaseSerializer`. :param plugins: list of :class:`aiocache.plugins.BasePlugin` derived classes. :param namespace: string to use as default prefix for the key used in all operations of the backend. Default is an empty string, "". :param timeout: int or float in seconds specifying maximum timeout for the operations to last. By default its 5. :param table_name: str with the name of the DynamoDB table. Default is "cache_table". :param region_name: str with the AWS region for DynamoDB. Default is "us-east-1". """NAME="dynamodb"def__init__(self, serializer=None, compress=False, **kwargs):
super().__init__(serializer=serializerorMsgSpecSerializer(compress=compress), **kwargs)
@classmethoddefparse_uri_path(cls, path):
return {}
def__repr__(self):
returnf"DynamoDBCache (table_name={self.table_name}, region_name={self.region_name})"
It is important to create a dynamodb table with a TTL column - the default table columns are
key_column: CacheKey
val_column: CacheValue
ttl_attribute_name: CacheTTL
The text was updated successfully, but these errors were encountered:
As I've mentioned elsewhere, it's probably best to create additional backends in separate libraries, rather than us trying to maintain dozens of backends. If you do this, then open an issue/PR to link to your backend from the README, then other users will be able to find it.
If would be great if this backend could be added to the list.
Here is an attempt:
It is important to create a dynamodb table with a TTL column - the default table columns are
CacheKey
CacheValue
CacheTTL
The text was updated successfully, but these errors were encountered: