|
| 1 | +from logging import getLogger |
| 2 | + |
| 3 | +from azure.core.exceptions import AzureError |
| 4 | +from azure.cosmos import CosmosClient, PartitionKey |
| 5 | +from azure.cosmos.container import ContainerProxy |
| 6 | +from azure.cosmos.database import DatabaseProxy |
| 7 | + |
| 8 | +from backend.settings.azure_cosmos_db import Settings |
| 9 | + |
| 10 | +logger = getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +class Client: |
| 14 | + def __init__(self, settings: Settings) -> None: |
| 15 | + self.settings = settings |
| 16 | + |
| 17 | + def get_client(self) -> CosmosClient: |
| 18 | + return CosmosClient.from_connection_string( |
| 19 | + conn_str=self.settings.azure_cosmos_db_connection_string, |
| 20 | + ) |
| 21 | + |
| 22 | + def get_database(self, database_id: str) -> DatabaseProxy: |
| 23 | + return self.get_client().get_database_client(database_id) |
| 24 | + |
| 25 | + def get_container(self, database_id: str, container_id: str) -> ContainerProxy: |
| 26 | + return self.get_database(database_id=database_id).get_container_client(container=container_id) |
| 27 | + |
| 28 | + def create_database(self, database_id: str) -> None: |
| 29 | + try: |
| 30 | + self.get_client().create_database_if_not_exists( |
| 31 | + id=database_id, |
| 32 | + ) |
| 33 | + except AzureError as e: |
| 34 | + logger.error(e) |
| 35 | + |
| 36 | + def create_container( |
| 37 | + self, |
| 38 | + database_id: str, |
| 39 | + container_id: str, |
| 40 | + partition_key_path="/id", |
| 41 | + ) -> None: |
| 42 | + try: |
| 43 | + self.get_database(database_id=database_id).create_container_if_not_exists( |
| 44 | + id=container_id, |
| 45 | + partition_key=PartitionKey( |
| 46 | + path=partition_key_path, |
| 47 | + ), |
| 48 | + ) |
| 49 | + except AzureError as e: |
| 50 | + logger.error(e) |
| 51 | + |
| 52 | + def create_item( |
| 53 | + self, |
| 54 | + container: ContainerProxy, |
| 55 | + item: dict, |
| 56 | + ) -> dict: |
| 57 | + return container.create_item( |
| 58 | + body=item, |
| 59 | + ) |
| 60 | + |
| 61 | + def read_item( |
| 62 | + self, |
| 63 | + container: ContainerProxy, |
| 64 | + item_id: str, |
| 65 | + ) -> dict: |
| 66 | + return container.read_item( |
| 67 | + item=item_id, |
| 68 | + partition_key=item_id, |
| 69 | + ) |
| 70 | + |
| 71 | + def query_items( |
| 72 | + self, |
| 73 | + container: ContainerProxy, |
| 74 | + query: str, |
| 75 | + parameters: list | None = None, |
| 76 | + enable_cross_partition_query: bool = True, |
| 77 | + ) -> list: |
| 78 | + return container.query_items( |
| 79 | + query=query, |
| 80 | + parameters=parameters, |
| 81 | + enable_cross_partition_query=enable_cross_partition_query, |
| 82 | + ) |
0 commit comments