Azure-Python-AI/AzureCosmosDB
1
1import os2import streamlit as st3from azure.cosmos import CosmosClient, PartitionKey4from azure.storage.blob import BlobServiceClient5from azure.cosmos.exceptions import CosmosResourceNotFoundError6import requests7import glob8from datetime import datetime9 10# Initialize Azure Clients11COSMOS_CONNECTION_STRING = os.getenv('COSMOS_CONNECTION_STRING')12BLOB_STORAGE_CONNECTION_STRING = os.getenv('BLOB_STORAGE_CONNECTION_STRING')13cosmos_client = CosmosClient.from_connection_string(COSMOS_CONNECTION_STRING)14blob_service = BlobServiceClient.from_connection_string(BLOB_STORAGE_CONNECTION_STRING)15 16# Function to Delete All Items in a Container17def delete_all_items_in_container(db_name, container_name):18 database_client = cosmos_client.get_database_client(db_name)19 container_client = database_client.get_container_client(container_name)20 21 for item in container_client.read_all_items():22 try:23 partition_key = '/id'24 container_client.delete_item(item=item['id'], partition_key=partition_key)25 st.write(f"Deleted Item: {item['id']}")26 except CosmosResourceNotFoundError:27 st.error(f"Item not found: {item['id']}")28 29 30# Display and Manage Cosmos DB Structure31def display_and_manage_cosmos_db():32 st.subheader('Azure Cosmos DB Structure')33 for db_properties in cosmos_client.list_databases():34 db_name = db_properties['id']35 st.markdown(f"#### Database: {db_name}")36 database_client = cosmos_client.get_database_client(db_name)37 38 for container_properties in database_client.list_containers():39 container_name = container_properties['id']40 st.markdown(f"- **Container**: {container_name}")41 container_client = database_client.get_container_client(container_name)42 43 for item in container_client.read_all_items():44 item_desc = f" - Item: `{item['id']}`"45 st.markdown(item_desc)46 if 'file_name' in item:47 st.image(item['file_name'])48 49 # Update and Delete buttons for each item50 if st.button(f"๐๏ธ Delete {item['id']}", key=f"delete_{item['id']}"):51 partition_key = '/id'52 container_client.delete_item(item=item['id'], partition_key=partition_key)53 st.success(f"Deleted Item: {item['id']}")54 55# Insert PNG Images with Unique Identifiers56def insert_png_images_with_unique_ids():57 db_name = st.selectbox("Select Database", [db['id'] for db in cosmos_client.list_databases()])58 container_name = st.selectbox("Select Container", [container['id'] for container in cosmos_client.get_database_client(db_name).list_containers()])59 container_client = cosmos_client.get_database_client(db_name).get_container_client(container_name)60 61 png_files = glob.glob('*.png')62 for file_name in png_files:63 unique_id = f"{os.path.splitext(file_name)[0]}_{datetime.now().strftime('%Y%m%d%H%M%S')}"64 item_data = {"id": unique_id, "file_name": file_name}65 container_client.create_item(body=item_data)66 st.write(f"Inserted Item: {unique_id}")67 68# Azure Blob Storage - Upload/Download69st.subheader('Azure Blob Storage - Upload/Download')70blob_container = st.text_input('Blob Container')71blob_file = st.file_uploader('Upload file to Blob')72 73if blob_file is not None and st.button('Upload to Blob'):74 blob_client = blob_service.get_blob_client(container=blob_container, blob=blob_file.name)75 blob_client.upload_blob(blob_file.getvalue())76 st.success('File uploaded successfully.')77 78# Azure Functions - Trigger79st.subheader('Azure Functions - Trigger')80function_url = st.text_input('Function URL')81 82if st.button('Call Azure Function'):83 response = requests.get(function_url)84 st.write('Function Response:', response.text)85 86 87# Display Cosmos DB Structure and Manage Items88display_and_manage_cosmos_db()89 90# Button to Insert PNG Images with Unique Identifiers91if st.button('Insert PNG Images with Unique IDs'):92 insert_png_images_with_unique_ids()93 94# Button to Delete All Items in a Container95db_name_to_delete = st.selectbox("Select Database to Delete From", [db['id'] for db in cosmos_client.list_databases()])96container_name_to_delete = st.selectbox("Select Container to Delete From", [container['id'] for container in cosmos_client.get_database_client(db_name_to_delete).list_containers()])97 98if st.button('Delete All Items in Container'):99 delete_all_items_in_container(db_name_to_delete, container_name_to_delete)100 st.success("All items deleted successfully.")101 