gpt4 book ai didi

python - Azure:使用容器创建存储帐户并在 Python 中将 blob 上传到其中

转载 作者:行者123 更新时间:2023-12-03 05:37:11 25 4
gpt4 key购买 nike

我正在尝试在 Azure 中创建一个存储帐户,并使用他们的 python SDK 将 blob 上传到其中。我设法创建了一个这样的帐户:

client = get_client_from_auth_file(StorageManagementClient)
storage_account = client.storage_accounts.create(
resourceGroup,
name,
StorageAccountCreateParameters(
sku=Sku(name=SkuName.standard_ragrs),
enable_https_traffic_only=True,
kind=Kind.storage,
location=region)).result()

问题是,后来我尝试构建一个容器,但我不知道要插入什么作为“account_url”我尝试过这样做:

client = get_client_from_auth_file(BlobServiceClient, account_url=storage_account.primary_endpoints.blob)
return client.create_container(name)

但我得到:

azure.core.exceptions.ResourceNotFoundError:指定的资源不存在

我确实设法使用以下方法创建了一个容器:

client = get_client_from_auth_file(StorageManagementClient)
return client.blob_containers.create(
resourceGroup,
storage_account.name,
name,
BlobContainer(),
public_access=PublicAccess.Container
)

但稍后当我尝试使用 BlobServiceClient 或 BlobClien 上传 blob 时,我仍然需要“account_url”,因此仍然收到错误:

azure.core.exceptions.ResourceNotFoundError:指定的资源不存在

任何人都可以帮助我了解如何获取我使用 SDK 创建的存储帐户的 account_url?

编辑:我设法通过从存储键创建连接字符串来找到解决该问题的方法。

storage_client = get_client_from_auth_file(StorageManagementClient)
storage_keys = storage_client.storage_accounts.list_keys(resource_group, account_name)
storage_key = next(v.value for v in storage_keys.keys)
return BlobServiceClient.from_connection_string(
'DefaultEndpointsProtocol=https;' +
f'AccountName={account_name};' +
f'AccountKey={storage_key};' +
'EndpointSuffix=core.windows.net')

这可行,但我认为乔治·陈的回答更优雅。

最佳答案

我可以重现这个问题,然后我发现get_client_from_auth_file无法将凭据传递给 BlobServiceClient ,因为如果只是创建 BlobServiceClientaccount_url没有凭据它也可以打印帐户名称。

因此,如果您想使用凭据来获取 BlobServiceClient,您可以使用以下代码,然后执行其他操作。

credentials = ClientSecretCredential(
'tenant_id',
'application_id',
'application_secret'
)

blobserviceclient=BlobServiceClient(account_url=storage_account.primary_endpoints.blob,credential=credentials)

如果您不希望这样,您可以创建 BlobServiceClient使用帐户 key 。

client = get_client_from_auth_file(StorageManagementClient,auth_path='auth')

storage_account = client.storage_accounts.create(
'group name',
'account name',
StorageAccountCreateParameters(
sku=Sku(name=SkuName.standard_ragrs),
enable_https_traffic_only=True,
kind=Kind.storage,
location='eastus',)).result()
storage_keys = client.storage_accounts.list_keys(resource_group_name='group name',account_name='account name')
storage_keys = {v.key_name: v.value for v in storage_keys.keys}
blobserviceclient=BlobServiceClient(account_url=storage_account.primary_endpoints.blob,credential=storage_keys['key1'])
blobserviceclient.create_container(name='container name')

关于python - Azure:使用容器创建存储帐户并在 Python 中将 blob 上传到其中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61611153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com