簡體   English   中英

下載 1 天 azure blob 文件 python

[英]Download 1 days azure blob file python

要求:

文件正在從各種機器上傳到 azure 容器中。 需要編寫一個 python 腳本從 azure 容器下載一天的文件,該容器將每天安排。

代碼:

import datetime
import os
import pytz

from azure.storage.blob import BlobClient, ContainerClient

utc=pytz.UTC
container_connection_string ="CONNECTION_STRING"
container_service_client = ContainerClient.from_connection_string(conn_str=container_connection_string, container_name="CONTAINER_NAME")

date_folder = start_time.strftime("%d-%m-%Y")
base_path = r"DOWNLOAD_PATH"
count = 0
threshold_time = utc.localize(start_time  - datetime.timedelta(days = 1))
blob_list = container_service_client.list_blobs()

if not os.path.exists("{}\{}".format(base_path, date_folder)):
    os.makedirs("{}\{}".format(base_path, date_folder))
print("Starting")

for ind, blob in enumerate(blob_list):
    if threshold_time < blob.last_modified:
        count += 1
        print(count, blob.name)
        blob_name = blob.name       
        blob = BlobClient.from_connection_string(conn_str=container_connection_string, container_name="CONTAINER_NAME", blob_name=blob_name)
        with open("{}\{}\{}".format(base_path, date_folder, blob_name), "wb") as my_blob:
            blob_data = blob.download_blob()
            blob_data.readinto(my_blob)

問題:

上面的腳本遍歷容器中的所有 blob 並檢查 blob 是否少於 1 天,如果是則下載它們。 由於每天有 15,000 多個文件被上傳到 blob 中,遍歷它們以識別今天的文件非常耗時,並且下載 blob 需要大量時間。

使用當前的方法,我相信除了枚舉 blob 並在客戶端過濾以找到匹配的 blob 之外別無他法。


但是我確實有一個替代解決方案。 這是一個有點復雜的解決方案,但我想我還是會提出:)。

本質上,該解決方案涉及使用Azure Event Grid並調用 Azure Function 在Microsoft.Storage.BlobCreated事件上被創建或替換時觸發。 此 Azure Function 會將 blob 復制到不同的 blob 容器。 現在每天都會創建一個新的 blob 容器,並且此 blob 容器將僅在當天保存 blob。 這使得迭代 blob 變得更加容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM