File size: 2,186 Bytes
1352a28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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