在存储帐户 python(天蓝色函数)之间移动或复制文件(blob)?

时间:2021-03-26 05:23:35

标签: python azure-functions azure-blob-storage blobstorage

我想使用 python(在 azure 函数中)在两个存储帐户之间移动(或复制然后删除)文件/blob。我使用过 this 之类的方法。 但是这适用于旧的 SDK,有人知道新 SDK 的方法吗?

类似于 this 但在两个存储帐户而不是容器之间。

1 个答案:

答案 0 :(得分:1)

如果要跨Azure存储账户复制blob,请参考以下代码

from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas, BlobServiceClient
from datetime import datetime, timedelta
source_key = ''
des_key = ''
source_account_name = ''
des_account_name = '23storage23'
# genearte account sas token for source account
sas_token = generate_account_sas(account_name=source_account_name, account_key=source_key,
                                 resource_types=ResourceTypes(
                                     service=True, container=True, object=True),
                                 permission=AccountSasPermissions(read=True),
                                 expiry=datetime.utcnow() + timedelta(hours=1))
source_blob_service_client = BlobServiceClient(
    account_url=f'https://{source_account_name}.blob.core.windows.net/', credential=source_key)
des_blob_service_client = BlobServiceClient(
    account_url=f'https://{des_account_name}.blob.core.windows.net/', credential=des_key)

source_container_client = source_blob_service_client.get_container_client(
    'copy')

source_blob = source_container_client.get_blob_client('Capture.PNG')
source_url = source_blob.url+'?'+sas_token
# copy
des_blob_service_client.get_blob_client(
    'test', source_blob.blob_name).start_copy_from_url(source_url)

另外,如果源容器的访问级别为public,我们可以将代码简化如下

from azure.storage.blob import BlobServiceClient
source_key = ''
des_key = ''
source_account_name = ''
des_account_name = '23storage23'
source_blob_service_client = BlobServiceClient(
    account_url=f'https://{source_account_name}.blob.core.windows.net/', credential=source_key)
des_blob_service_client = BlobServiceClient(
    account_url=f'https://{des_account_name}.blob.core.windows.net/', credential=des_key)

source_container_client = source_blob_service_client.get_container_client(
    'input')

source_blob = source_container_client.get_blob_client('file.json')
source_url = source_blob.url
# copy
des_blob_service_client.get_blob_client(
    'test', source_blob.blob_name).start_copy_from_url(source_url)

enter image description here 详情请参阅here

enter image description here