from azure.storage.blob import BlobServiceClient, BlobClient, ContentSettings, generate_blob_sas, BlobSasPermissions from datetime import datetime, timedelta import os import dotenv dotenv.load_dotenv() storage_account_name = os.environ['AZURE_STORAGE_ACCOUNT_NAME'] storage_account_key = os.environ['AZURE_STORAGE_KEY'] connection_string = os.environ['AZURE_STORAGE_CONNECTION_STRING'] container_name = os.environ['AZURE_STORAGE_CONTAINER_NAME'] def upload_image_to_blob(image_data, image_name): # Create a BlobServiceClient blob_service_client = BlobServiceClient(account_url=f"https://{storage_account_name}.blob.core.windows.net", credential=storage_account_key) # Get the container client container_client = blob_service_client.get_container_client(container_name) # get the extension # extension = os.path.splitext(image_name)[1] # Get the blob client for the image blob_name = image_name blob_client = container_client.get_blob_client(blob_name) # Determine the content type from the image name content_type = "image/jpeg" # Default to JPEG if image_name.lower().endswith(".png"): content_type = "image/png" elif image_name.lower().endswith(".gif"): content_type = "image/gif" # Create the content settings with the determined content type content_settings = ContentSettings(content_type=content_type) # Set the content settings for the blob # blob_client.set_http_headers(content_settings) # Upload the image blob_client.upload_blob(image_data, content_settings=content_settings) # Generate a SAS token for the blob sas_token = generate_blob_sas( account_name=storage_account_name, container_name=container_name, blob_name=blob_name, account_key=storage_account_key, permission=BlobSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=10) # The SAS token will be valid for 1 hour ) # Create a SAS URL for the blob sas_url = f"https://{storage_account_name}.blob.core.windows.net/{container_name}/{blob_name}?{sas_token}" return sas_url