Uploading a blob in Azure Storage

Kepler·2020년 7월 31일
0

Assuming, you already have pre-defined storage and container in Azure, here is how to upload a blob into the container.

Uploading a file from your local storage

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, ContentSettings

CONNECT_STR = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
CONTAINER_NAME = os.getenv('AZURE_STORAGE_CONTAINER_NAME')

# Instantiate a ContainerClient. This is used when uploading a blob from your local file.
container_client = ContainerClient.from_connection_string(
    conn_str=CONNECT_STR, 
    container_name=CONTAINER_NAME
)

input_file_path = "/users/kepler/Downloads/TEST_PIC.jpeg"
output_blob_name = "BLOB_PIC.jpeg"

#This is an optional setting for guaranteeing the MIME type to be always jpeg.
content_setting = ContentSettings(
    content_type='image/jpeg', 
    content_encoding=None, 
    content_language=None, 
    content_disposition=None, 
    cache_control=None, 
    content_md5=None
)

# Upload file
with open(input_file_path, "rb") as data:
     container_client.upload_blob(
         name=output_blob_name, 
         data=data, 
         content_settings=content_setting)
         
# Check the result
all_blobs = container_client.list_blobs(name_starts_with="BLOB_PIC", include=None)
for each in all_blobs:
    print("RES: ", each)

Uploading a URL file


blob_service_client = BlobServiceClient.from_connection_string(conn_str=CONNECT_STR)

# State the url
source_blob = 'https://i.picsum.photos/id/72/200/200.jpg?hmac=SvHJdhApYL5YL48lV8qJ_QmrFZ2IzRcMEt3Jf4-O1X0'
copied_blob = blob_service_client.get_blob_client(CONTAINER_NAME, 'BLOB_VIA_URL.jpeg')

# start copy and check copy status
copy = copied_blob.start_copy_from_url(source_blob)
props = copied_blob.get_blob_properties()
print(props.copy.status)
# [END copy_blob_from_url]


  
profile
🔰

0개의 댓글