Azure Cosmos DB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
https://docs.microsoft.com/en-us/azure/cosmos-db/sql/create-sql-api-python | |
https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/cosmos/azure-cosmos/samples/examples.py | |
Pre-Req: | |
pip install --pre azure-cosmos | |
Have a Azure Account with Free Subscribption Enabled | |
Make sure Cosmosa DB is created along with DB and Container | |
#Azure portal > Azure Cosmos > ck on Existing Cosmos Db > Settings > Keys | |
to get Primary key and endpoint | |
""" | |
from azure.cosmos import exceptions, CosmosClient, PartitionKey | |
import uuid | |
import json | |
endpoint = "GET KEYS FROM : Azure portal > Azure Cosmos > ck on Existing Cosmos Db > Settings > Keys" | |
key = 'GET KEYS FROM : Azure portal > Azure Cosmos > ck on Existing Cosmos Db > Settings > Keys' | |
jsondata= {"id": "3","category": "hobby","name": "TV","description": "Pick up TV"} | |
dbname="ToDoDatabase" | |
containerid="ToDoList" | |
query="SELECT * FROM ITEMS" | |
class CosmosDb(): | |
def __init__(self,endpoint,key,dbname,containerid): | |
self.endpoint=endpoint | |
self.key=key | |
self.client = CosmosClient(endpoint, key) | |
self.database = self.client.get_database_client(database=dbname) #create_database_if_not_exists | |
self.container = self.database.get_container_client(containerid) #create_container_if_not_exists | |
def create_item(self,jsondata): | |
self.container.create_item(body=jsondata) | |
def list_containers(self,database_name): | |
database = self.client.get_database_client(database_name) | |
return database.list_containers() | |
def modify_item(self,item_name,partition,key,new_value): | |
item = self.container.read_item(item_name, partition_key=partition) | |
item[key] = new_value | |
updated_item = container.upsert_item(item) | |
def query_items(self,query:str): | |
return self.container.query_items(query=query,enable_cross_partition_query=True) | |
cosmos=CosmosDb(endpoint,key,dbname,containerid) | |
# res=cosmos.list_containers(dbname) | |
res=cosmos.query_items("SELECT * FROM ITEMS") | |
for i in res : print(json.dumps(i,indent=True)) | |
No comments:
Post a Comment