forked from Azure-Samples/cosmos-db-nosql-python-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
68 lines (54 loc) · 1.79 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Sample showing how to connect with endpoint and key."""
# <imports>
import json
import os
import sys
import uuid
from azure.core.exceptions import AzureError
from azure.cosmos import CosmosClient, PartitionKey
# </imports>
DATABASE_ID = "cosmicworks"
CONTAINER_ID = "products"
# <client>
ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]
client = CosmosClient(url=ENDPOINT, credential=KEY)
# </client>
def main():
"""How to CosmosDB and NoSQL samples."""
try:
# Create database and partition key.
database = client.create_database_if_not_exists(id=DATABASE_ID)
# Create a container.
partition_key_path = PartitionKey(path="/categoryId")
container = database.create_container_if_not_exists(
id=CONTAINER_ID,
partition_key=partition_key_path,
offer_throughput=400,
)
# Create a new item.
new_guid = str(uuid.uuid4())
new_item = {
"id": new_guid,
"categoryId": "61dba35b-4f02-45c5-b648-c6badc0cbd79",
"categoryName": "gear-surf-surfboards",
"name": "Yamba Surfboard",
"quantity": 12,
"sale": False,
}
container.create_item(new_item)
# Query items.
sql_stmt = "SELECT * FROM products p WHERE p.categoryId = @categoryId"
category_id = "61dba35b-4f02-45c5-b648-c6badc0cbd79"
params = [dict(name="@categoryId", value=category_id)]
items = container.query_items(
query=sql_stmt,
parameters=params,
enable_cross_partition_query=False,
)
for item in items:
print(json.dumps(item, indent=True))
except AzureError as err:
sys.exit("Error:" + str(err))
if __name__ == "__main__":
main()