Skip to content

Commit ad9f889

Browse files
committed
refactor cosmos db script
1 parent 5e8d31d commit ad9f889

File tree

2 files changed

+85
-38
lines changed

2 files changed

+85
-38
lines changed

apps/3_call_azure_cosmos_db/README.md

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,29 +32,38 @@ $ python apps/3_call_azure_cosmos_db/main.py Hello
3232
### Example
3333

3434
```shell
35-
$ python apps/3_call_azure_cosmos_db/main.py Hello
36-
Created item:
35+
$ python apps/3_call_azure_cosmos_db/main.py --command create
36+
Create item
3737
{'_attachments': 'attachments/',
38-
'_etag': '"8100471f-0000-2300-0000-66b32f2b0000"',
39-
'_rid': 'Ny9FAOMmTIMKAAAAAAAAAA==',
40-
'_self': 'dbs/Ny9FAA==/colls/Ny9FAOMmTIM=/docs/Ny9FAOMmTIMKAAAAAAAAAA==/',
41-
'_ts': 1723019051,
38+
'_etag': '"0000ef9c-0000-2300-0000-66dfd5140000"',
39+
'_rid': 'ipcwAJFKMxICAAAAAAAAAA==',
40+
'_self': 'dbs/ipcwAA==/colls/ipcwAJFKMxI=/docs/ipcwAJFKMxICAAAAAAAAAA==/',
41+
'_ts': 1725945108,
4242
'content': 'Hello, world!',
43-
'id': 'Hello',
43+
'id': 'test',
4444
'role': 'assistant'}
45+
46+
$ python apps/3_call_azure_cosmos_db/main.py --command read
4547
Read item:
4648
{'_attachments': 'attachments/',
47-
'_etag': '"8100471f-0000-2300-0000-66b32f2b0000"',
48-
'_rid': 'Ny9FAOMmTIMKAAAAAAAAAA==',
49-
'_self': 'dbs/Ny9FAA==/colls/Ny9FAOMmTIM=/docs/Ny9FAOMmTIMKAAAAAAAAAA==/',
50-
'_ts': 1723019051,
49+
'_etag': '"0000ef9c-0000-2300-0000-66dfd5140000"',
50+
'_rid': 'ipcwAJFKMxICAAAAAAAAAA==',
51+
'_self': 'dbs/ipcwAA==/colls/ipcwAJFKMxI=/docs/ipcwAJFKMxICAAAAAAAAAA==/',
52+
'_ts': 1725945108,
5153
'content': 'Hello, world!',
52-
'id': 'Hello',
54+
'id': 'test',
5355
'role': 'assistant'}
56+
57+
$ python apps/3_call_azure_cosmos_db/main.py --command delete
58+
Delete item:
59+
60+
$ python apps/3_call_azure_cosmos_db/main.py --command read
61+
Read item:
62+
Failed to read item: (NotFound) Entity with the specified id does not exist in the system. More info: https://aka.ms/cosmosdb-tsg-not-found,
5463
```
5564

5665
## References
5766

58-
- [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)
59-
- [Examples for Azure Cosmos DB for NoSQL SDK for Python](https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/samples-python)
67+
- [Get started with Azure Cosmos DB for NoSQL using Python](https://learn.microsoft.com/azure/cosmos-db/nosql/how-to-python-get-started?tabs=env-virtual%2Cazure-cli%2Clinux)
68+
- [Examples for Azure Cosmos DB for NoSQL SDK for Python](https://learn.microsoft.com/azure/cosmos-db/nosql/samples-python)
6069
- [Azure Cosmos DB SQL API client library for Python Samples](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/cosmos/azure-cosmos/samples)
Lines changed: 62 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,43 @@
1+
import argparse
2+
import logging
13
import sys
24
from os import getenv
35
from pprint import pprint
46

57
from azure.cosmos import CosmosClient, PartitionKey
68
from dotenv import load_dotenv
79

10+
11+
def init_args() -> argparse.Namespace:
12+
parser = argparse.ArgumentParser(
13+
prog="cosmosdb",
14+
description="",
15+
)
16+
parser.add_argument("-i", "--item-id", default="test", help="Item ID")
17+
parser.add_argument("-p", "--partition-key-path", default="/id", help="Partition key")
18+
parser.add_argument("-v", "--verbose", action="store_true")
19+
parser.add_argument("-c", "--command", default="create", help="Command to execute: create, read, delete")
20+
return parser.parse_args()
21+
22+
823
if __name__ == "__main__":
24+
args = init_args()
25+
26+
# Set verbose mode
27+
if args.verbose:
28+
logging.basicConfig(level=logging.DEBUG)
29+
930
# Parse .env file and get environment variables
1031
load_dotenv()
1132

12-
# Get item_id from command line arguments
13-
if len(sys.argv) < 2:
14-
print("Usage: python main.py <item_id>")
15-
sys.exit(1)
16-
item_id = sys.argv[1]
33+
item_id = args.item_id
1734

1835
# Connect to Azure Cosmos DB
1936
try:
2037
client = CosmosClient.from_connection_string(getenv("AZURE_COSMOS_DB_CONNECTION_STRING"))
2138
database = client.create_database_if_not_exists(id=getenv("AZURE_COSMOS_DB_DATABASE_NAME"))
2239
partition_key_path = PartitionKey(
23-
path="/id",
40+
path=args.partition_key_path,
2441
kind="Hash",
2542
)
2643
container = database.create_container_if_not_exists(
@@ -31,24 +48,45 @@
3148
print(f"Failed to connect to Azure Cosmos DB: {e}")
3249
sys.exit(1)
3350

34-
# Create and read an item
35-
try:
36-
response = container.create_item(
37-
body={
38-
"id": item_id,
39-
"role": "assistant",
40-
"content": "Hello, world!",
41-
}
42-
)
43-
print("Created item:")
44-
pprint(response)
45-
response = container.read_item(
46-
item=item_id,
47-
partition_key=item_id,
48-
)
51+
if args.command == "create":
52+
# Create and read an item
53+
print("Create item")
54+
try:
55+
response = container.create_item(
56+
body={
57+
"id": item_id,
58+
"role": "assistant",
59+
"content": "Hello, world!",
60+
}
61+
)
62+
pprint(response)
63+
except Exception as e:
64+
print(f"Failed to create item: {e}")
65+
sys.exit(1)
66+
elif args.command == "read":
67+
# Read an item
4968
print("Read item:")
50-
pprint(response)
69+
try:
70+
response = container.read_item(
71+
item=item_id,
72+
partition_key=item_id,
73+
)
74+
pprint(response)
5175

52-
except Exception as e:
53-
print(f"Failed to create item: {e}")
76+
except Exception as e:
77+
print(f"Failed to read item: {e}")
78+
sys.exit(1)
79+
elif args.command == "delete":
80+
# Delete an item
81+
print("Delete item:")
82+
try:
83+
container.delete_item(
84+
item=item_id,
85+
partition_key=item_id,
86+
)
87+
except Exception as e:
88+
print(f"Failed to delete item: {e}")
89+
sys.exit(1)
90+
else:
91+
print(f"Invalid command {args.command}")
5492
sys.exit(1)

0 commit comments

Comments
 (0)