Skip to content

Commit bb544ef

Browse files
committed
implement cosmosdb internal package
1 parent e9651a0 commit bb544ef

File tree

7 files changed

+121
-98
lines changed

7 files changed

+121
-98
lines changed

azure_cosmos_db.env.sample

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
AZURE_COSMOS_DB_ENDPOINT = "<cosmosdb-endpoint>"
2+
AZURE_COSMOS_DB_KEY = "<cosmosdb-key>"
3+
AZURE_COSMOS_DB_CONNECTION_STRING = "<cosmosdb-connection-string>"
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
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+
)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from pydantic_settings import BaseSettings, SettingsConfigDict
2+
3+
4+
class Settings(BaseSettings):
5+
azure_cosmos_db_endpoint: str = "https://<your-cosmos-db-name>.documents.azure.com:443/"
6+
azure_cosmos_db_key: str = "<your-cosmos-db-key>"
7+
azure_cosmos_db_connection_string: str = "<your-cosmos-db-connection-string>"
8+
9+
model_config = SettingsConfigDict(
10+
env_file="azure_cosmos_db.env",
11+
env_file_encoding="utf-8",
12+
extra="ignore",
13+
)

docs/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,7 @@
6464
### Azure Cosmos DB
6565

6666
- [Manage Azure Cosmos DB for NoSQL resources with Bicep > Azure Cosmos DB account with autoscale throughput](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/manage-with-bicep#azure-cosmos-db-account-with-autoscale-throughput)
67+
- [Get started with Azure Cosmos DB for NoSQL using Python](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-python-get-started?tabs=env-virtual%2Cazure-cli%2Clinux)
68+
- [Create a database in Azure Cosmos DB for NoSQL using Python](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-python-create-database)
69+
- [Create a container in Azure Cosmos DB for NoSQL using Python](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-python-create-container)
70+
- [Sample - demonstrates the basic CRUD operations on a Item resource for Azure Cosmos](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/samples/document_management.py)

infra/modules/cosmosDb.bicep

Lines changed: 2 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,6 @@ param tags object = {}
1111
@description('Specifies the name of the Azure Cosmos DB account name, max length 44 characters, lowercase.')
1212
param accountName string = toLower('${name}account')
1313

14-
@description('Specifies the name of the Azure Cosmos DB database name')
15-
param databaseName string = toLower('${name}database')
16-
17-
@description('Specifies the name of the Azure Cosmos DB container name')
18-
param containerName string = toLower('${name}container')
19-
2014
@description('The primary region for the Cosmos DB account.')
2115
param primaryRegion string
2216

@@ -46,11 +40,6 @@ param maxIntervalInSeconds int = 300
4640
@description('Enable system managed failover for regions')
4741
param systemManagedFailover bool = true
4842

49-
@description('Maximum autoscale throughput for the container')
50-
@minValue(1000)
51-
@maxValue(1000000)
52-
param autoscaleMaxThroughput int = 1000
53-
5443
var consistencyPolicy = {
5544
Eventual: {
5645
defaultConsistencyLevel: 'Eventual'
@@ -96,91 +85,7 @@ resource account 'Microsoft.DocumentDB/databaseAccounts@2024-02-15-preview' = {
9685
}
9786
}
9887

99-
resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2024-02-15-preview' = {
100-
parent: account
101-
name: databaseName
102-
location: location
103-
tags: tags
104-
properties: {
105-
resource: {
106-
id: databaseName
107-
}
108-
}
109-
}
110-
111-
resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2024-02-15-preview' = {
112-
parent: database
113-
name: containerName
114-
location: location
115-
tags: tags
116-
properties: {
117-
resource: {
118-
id: containerName
119-
partitionKey: {
120-
paths: [
121-
'/myPartitionKey'
122-
]
123-
kind: 'Hash'
124-
}
125-
indexingPolicy: {
126-
indexingMode: 'consistent'
127-
includedPaths: [
128-
{
129-
path: '/*'
130-
}
131-
]
132-
excludedPaths: [
133-
{
134-
path: '/myPathToNotIndex/*'
135-
}
136-
{
137-
path: '/_etag/?'
138-
}
139-
]
140-
compositeIndexes: [
141-
[
142-
{
143-
path: '/name'
144-
order: 'ascending'
145-
}
146-
{
147-
path: '/age'
148-
order: 'descending'
149-
}
150-
]
151-
]
152-
spatialIndexes: [
153-
{
154-
path: '/path/to/geojson/property/?'
155-
types: [
156-
'Point'
157-
'Polygon'
158-
'MultiPolygon'
159-
'LineString'
160-
]
161-
}
162-
]
163-
}
164-
defaultTtl: 86400
165-
uniqueKeyPolicy: {
166-
uniqueKeys: [
167-
{
168-
paths: [
169-
'/phoneNumber'
170-
]
171-
}
172-
]
173-
}
174-
}
175-
options: {
176-
autoscaleSettings: {
177-
maxThroughput: autoscaleMaxThroughput
178-
}
179-
}
180-
}
181-
}
182-
18388
// Outputs
18489
output accountId string = account.id
185-
output databaseId string = database.id
186-
output containerId string = container.id
90+
output accountName string = account.name
91+
output accountEndpoint string = account.properties.documentEndpoint

poetry.lock

Lines changed: 16 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ azure-storage-blob = "^12.19.1"
3333
azure-ai-vision-imageanalysis = "^1.0.0b2"
3434
azure-eventgrid = "^4.19.0"
3535
azure-storage-queue = "^12.9.0"
36+
azure-cosmos = "^4.6.1"
3637

3738

3839
[tool.poetry.group.frontend.dependencies]

0 commit comments

Comments
 (0)