简体   繁体   English

为什么 Python Azure function 应用程序不将单个文件从存储帐户中的目录复制到目录?

[英]Why Python Azure function app not copying single file from directory to directory in Storage account?

I have a Azure function app developed in Python which checks if any blobs available at a specific folder.我有一个在 Python 中开发的 Azure function 应用程序,它检查特定文件夹中是否有可用的 blob。
If blobs exists, loop through all blobs and copy them into another directory in the same storage account.如果 blob 存在,则遍历所有 blob 并将它们复制到同一存储帐户中的另一个目录中。
I have a code which is checking for file existence but loop is failing when only one single file is there in the container.我有一个代码正在检查文件是否存在,但是当容器中只有一个文件时循环失败。 Not sure why.不知道为什么。

blob_service_client = BlobServiceClient.from_connection_string(os.getenv('AzureWebJobsStorage'))
container_ref = blob_service_client.get_container_client('container')
blobs = container_ref.list_blobs(name_starts_with='incoming/srcerx/')
blob_list = []
for s in blobs: #blobs have value of a blob, so loop starts
    blob_list.append(s)
    #use break to make sure only one iteration to avoid iterating all the blobs
    break
if len(blob_list) > 0: #length is 1 coming here
    fileCount = 0
    #move all blobs to dated directory in the same container
    for s in blobs: #not entering loop if only one blob is there
        print(s.name.replace('incoming/srcerx/',''))
        fileCount+=1
        moveBlobs(s.name)

I am not sure what wrong I am doing here.我不确定我在这里做错了什么。 I tested this code with 1000 files, it copied all 999 files but left one.我用 1000 个文件测试了这段代码,它复制了所有 999 个文件但留下了一个。
It would be better if somebody suggest any better idea to load all blobs without loop in Python.如果有人建议在 Python 中加载所有不带循环的 blob 更好的主意,那就更好了。

Use blow code:使用打击代码:

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

connect_str = "DefaultEndpointsProtocol=https;AccountName=0730bowmanwindow;AccountKey=xxxxxx;EndpointSuffix=core.windows.net"
container_name = "test"

blob_service_client = BlobServiceClient.from_connection_string(connect_str)

container_name = "test"
container_client = blob_service_client.get_container_client(container_name)
blobs = container_client.list_blobs(name_starts_with="incoming/srcerx/")

num = 0

for blob in blobs:
    from_blobname = blob.name
    from_blob_client = blob_service_client.get_blob_client(container=container_name,blob=from_blobname)
    from_blob_url = from_blob_client.primary_endpoint

    file_name = from_blobname.replace("incoming/srcerx/","")
    to_blobname = "incoming/srcerx2/"+file_name
    to_blob_client = blob_service_client.get_blob_client(container=container_name,blob=to_blobname)
    to_blob_client.start_copy_from_url(from_blob_url)
    num = num + 1
    print(num)

Above code copy all of the files:上面的代码复制所有文件:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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