简体   繁体   中英

Conditional Delete Azure blob storage using python

Im trying to create a script where it delete all the file in the blob when the creation date of the file > 15 days. i'm able to delete the blob using the code below but i coudn't find a way to access creation date from azure and then delete the file

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__
storage_account_key = "KEY"
storage_account_name = "STORAGE NAME"
connection_string = "connection STRING "
container_name = "Connection String"
blob_name="blob storage
container_client = ContainerClient.from_connection_string(conn_str=connection_string, 
container_name=container_name)
container_client.delete_blob(blob=blob_name)

What you need to do is get the blob properties using BlobClient.get_blob_properties() method. Once you get the properties , you can find the blob's created date/time in creation_time property.

Your code would be something like:

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__
storage_account_key = "KEY"
storage_account_name = "STORAGE NAME"
connection_string = "connection STRING "
container_name = "Connection String"
blob_name="blob storage
container_client = ContainerClient.from_connection_string(conn_str=connection_string, 
container_name=container_name)
blob_client = container_client.get_blob_client(blob=blob_name)
blob_properties = blob_client.get_blob_properties()
#Check for creation time and then delete blob if needed
if blob_properties.creation_time > 'some date time value'
  blob_client.delete_blob()

Adding to @Gaurav Mantri, Below is the code where you can check if the creation date is greater than 15 days and delete if it is.

blob_client = container_client.get_blob_client(blob=blob_name)

blob_properties = blob_client.get_blob_properties()

creation_time=str(blob_properties.creation_time)
d1 = creation_time[0:creation_time.index(" ")]
today = str(datetime.today())
d2 = creation_time[0:today.index(" ")]
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
Threshold=abs((d2 - d1).days)

if Threshold==0:
    blob_client.delete_blob()
    print(blob_name +" got deleted")

RESULTS:

在此处输入图像描述

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