简体   繁体   中英

Can't Set Properties for Azure Blob with Azure SDK for Python

I am trying to set properties of the files inside my blob location but somehow it's not persistent.

from azure.storage.blob import BlobServiceClient, ContentSettings
connect_str="connectionString"
blob_service_client = BlobServiceClient.from_connection_string(connect_str)

# Instantiate a ContainerClient
container_client = blob_service_client.get_container_client("$web")

# List files in blob folder
blobs_list = container_client.list_blobs()
for blob in blobs_list:
    print(blob.content_settings.content_type) # application/octet-stream
    blob.content_settings.content_type="text/html; charset=utf-8"
    print(blob.content_settings.content_type)

Output:

application/octet-stream

text/html; charset=utf-8

But when I again try to run:

blobs_list = container_client.list_blobs()
for blob in blobs_list:
    print(blob.content_settings.content_type)

I still get application/octet-stream which I am not able to understand why?

You changed a local variable, you need an explicit call to change the property on Azure itself. You need to build a blobclient and to call set_http_headers . From inside your loop:

    blob_client = container_client.get_blob_client(blob)
    blob_client.set_http_headers(
        content_settings=ContentSettings(
            content_type="text/html; charset=utf-8"
        )
    )

Feel free to open an issue in the Azure SDK for Python if you feel this sample should be easier to find: https://github.com/Azure/azure-sdk-for-python/issues

(I work at MS in the Python SDK team)

When we do blob.content_settings.content_type="text/html; charset=utf-8" this only changes the variable on your local machine ( no requests are being sent to change this value ). It is essentially like setting any other variable within your Python program.

If you want this value to persist on your storage account you must send out a request. In order to change this value you'd have to do something like:

from azure.storage.blob import BlobServiceClient, ContentSettings
connect_str="connectionString"
blob_service_client = BlobServiceClient.from_connection_string(connect_str)

# Instantiate a ContainerClient
container_client = blob_service_client.get_container_client("$web")

# List files in blob folder
blobs_list = container_client.list_blobs()
for blob in blobs_list:
    print(blob.content_settings.content_type) # application/octet-stream
    blob.set_http_headers(
    content_settings=ContentSettings(
        content_type="text/html; charset=utf-8"
        )
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM