from azure.cosmos import cosmos_client
import json
"""
Expecting Dictionary for the secret in the following format:
{
"ENDPOINT": "<ENDPOINT>",
"PRIMARYKEY": "<PRIMARYKEY>",
"DATABASE": "<DATABASE>",
"CONTAINER": "<CONTAINER>"
}
Change out the following values with the appropriate values from your Azure account:
<ENDPOINT> - Get from Azure account
<PRIMARYKEY> - Get from Azure account
<DATABASE> - Database to connect to
<CONTAINER> - Container to use
"""
credentials = None
with open('/var/run/secrets/user_credentials/<credential_key>') as f:
credentials = json.load(f)
# Initialize the Cosmos client
client = cosmos_client.CosmosClient(
url_connection=credentials.get('ENDPOINT'),
auth={'masterKey': credentials.get('PRIMARYKEY')}
)
def find_element(id, element_type, parent_link=None):
item = None
temp_items = []
find_entity_by_id_query = {
"query": "SELECT * FROM r WHERE r.id=@id",
"parameters": [
{ "name":"@id", "value": id}
]
}
if element_type == 'database':
temp_items = list(client.QueryDatabases(find_entity_by_id_query))
elif element_type == 'collection':
temp_items = list(client.QueryContainers(parent_link, find_entity_by_id_query))
if len(temp_items) == 1:
item = temp_items[0]
return item
database = find_element(credentials.get('DATABASE'), 'database')
collection = find_element(credentials.get('CONTAINER'), 'collection', database.get('_self'))
query = {'query': 'SELECT * FROM c'}
options = {'enableCrossPartitionQuery': True}
results = client.QueryItems(collection.get('_self'), query, options)
for result in results:
print(json.dumps(result, indent=4))