跳到主要内容

cache.cosmos_db_cache

CosmosDB缓存

class CosmosDBCache(AbstractCache)

使用Azure Cosmos DB NoSQL API同步实现AbstractCache。

该类提供了使用Azure Cosmos DB进行数据缓存的AbstractCache接口的具体实现,支持同步操作。

属性:

  • seed Union[str, int] - 用作分区键的种子或命名空间。
  • client CosmosClient - 用于缓存的Cosmos DB客户端。
  • container - 用于缓存的容器实例。

__init__

def __init__(seed: Union[str, int], cosmosdb_config: CosmosDBConfig)

初始化CosmosDBCache实例。

参数:

  • seed Union[str, int] - 用于缓存的种子或命名空间,作为分区键使用。
  • connection_string str - Cosmos DB 帐户的连接字符串。
  • container_id str - 用于缓存的容器ID。
  • client Optional[CosmosClient] - 用于缓存的现有CosmosClient实例。

create_cache

@classmethod
def create_cache(cls, seed: Union[str, int], cosmosdb_config: CosmosDBConfig)

工厂方法,用于根据提供的配置创建CosmosDBCache实例。 此方法决定是否使用现有的CosmosClient或创建一个新的。

获取

def get(key: str, default: Optional[Any] = None) -> Optional[Any]

从 Cosmos DB 缓存中检索一个项目。

参数:

  • key str - 用于标识缓存中项目的键。
  • default 可选 - 如果未找到键,则返回的默认值。

返回:

如果找到与键关联的反序列化值,则返回该值,否则返回默认值。

设置

def set(key: str, value: Any) -> None

在Cosmos DB缓存中设置一个项目。

参数:

  • key str - 用于存储项的键。
  • value - 要存储在缓存中的值。

注意:

该值在存储之前使用pickle进行序列化。

关闭

def close() -> None

关闭Cosmos DB客户端。

执行任何必要的清理工作,例如关闭网络连接。

__enter__

def __enter__()

上下文管理入口。

返回:

  • self - 实例本身。

__exit__

def __exit__(exc_type: Optional[type], exc_value: Optional[Exception],
traceback: Optional[Any]) -> None

上下文管理退出。

执行清理操作,例如关闭 Cosmos DB 客户端。