python 我试图搜索和下载一个文件从Azure的二进制大对象存储和即时通讯抛出错误

v440hwme  于 2023-08-02  发布在  Python
关注(0)|答案(1)|浏览(96)

下面是我的查询:
找到的文件= []

for blob in blob_list:
    if search_query.lower() in blob.name.lower():
        found_files.append(blob.name)
        blob_client = container_client.get_blob_client(blob.name)
        try:
            blob_data = download_blob_with_retry(blob_client)
            with open(f"{local_download_path}/{blob.name}", "wb") as f:
                f.write(blob_data)
        except ResourceNotFoundError as ex:
            print(f"Blob not found: {ex}")
        except Exception as ex:
            print(f"Error downloading blob: {ex}")

字符串
IM抛出错误:
无法流式下载:(“连接断开:InvalidChunkLength(got length b'',0 bytes read)",InvalidChunkLength(got length b'',0 bytes read))

jdgnovmf

jdgnovmf1#

首先,我上传了一个文件夹,其中有三个文件作为blob到我的存储帐户容器中,如下所示:


的数据

我对您的代码进行了一些更改,可以从我的存储帐户容器下载blob。
验证码:

import os
import time
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
from azure.core.exceptions import ResourceNotFoundError

connection_string = "<connec_string>"
container_name = "<container_name>"
local_download_path = "<path/to/save the downloaded file>"
search_query = "<storage_blob_name>"

def download_blob_with_retry(blob_client, max_retries=5, retry_delay=2):
    for retry_count in range(max_retries):
        try:
            blob_data = blob_client.download_blob().readall()
            return blob_data
        except Exception as ex:
            print(f"Error downloading blob: {ex}")
            print(f"Retrying ({retry_count + 1}/{max_retries})...")
            time.sleep(retry_delay)

    print("Failed to download blob after multiple retries.")
    return None

try:
    blob_service_client = BlobServiceClient.from_connection_string(connection_string)
    container_client = blob_service_client.get_container_client(container_name)

    blob_list = container_client.list_blobs()

    found_files = []

    for blob in blob_list:
        if search_query.lower() in blob.name.lower():
            found_files.append(blob.name)
            blob_client = container_client.get_blob_client(blob.name)
            try:
                os.makedirs(os.path.dirname(os.path.join(local_download_path, blob.name)), exist_ok=True)
                
                blob_data = download_blob_with_retry(blob_client)
                if blob_data is not None:
                    with open(os.path.join(local_download_path, blob.name), "wb") as f:
                        f.write(blob_data)
                    print(f"Blob downloaded successfully: {blob.name}")
            except ResourceNotFoundError as ex:
                print(f"Blob not found: {ex}")
            except Exception as ex:
                print(f"Error downloading blob: {ex}")

except Exception as ex:
    print(f"Error connecting to Azure Blob Storage: {ex}")

字符串

输出:

成功运行如下,


  • 并从存储帐户容器中下载文件夹中的blob到给定路径,如下所示 *,


相关问题