python - 如何使用 Azure Python SDK 为容器创建共享访问签名

标签 python azure sdk azure-storage azure-blob-storage

我正在尝试使用 Azure Python SDK 为 Azure 存储中的容器创建有效的共享访问签名 URL。我试图将其生成为立即生效、30 天后过期,并提供对整个容器(而不仅仅是 blob)的读写访问权限。下面的代码工作正常,并在最后打印最终的 URL。我还在门户中手动验证了容器和 blob 是否已成功创建。

但是,将 URL 粘贴到浏览器后,我收到以下错误消息:

<?xml version="1.0" encoding="UTF-8"?>

-<Error>

<Code>AuthenticationFailed</Code>

<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:adecbe4e-0001-007c-0d19-40670c000000 Time:2015-12-26T20:10:45.9030215Z</Message>

<AuthenticationErrorDetail>Signature fields not well formed.</AuthenticationErrorDetail>

</Error>

看来问题一定出在这行代码上:

sasToken = blob_service.generate_shared_access_signature(containerName, None,SharedAccessPolicy(AccessPolicy(None, todayPlusMonthISO, "rw"), None))

这是完整的代码示例:

from azure.storage.blob import BlobService
import datetime
from azure.storage import AccessPolicy, CloudStorageAccount, SharedAccessPolicy

containerName = "testcontainer"
blobName = "testblob.txt"
azureStorageAccountName = "" # Removed for publishing to StackOverflow
azureStorageAccountKey = "" # Removed for publishing to StackOverflow
blob_service = BlobService(account_name=azureStorageAccountName, account_key=azureStorageAccountKey)
blob_service.create_container(containerName)
blob_service.put_block_blob_from_text(containerName,blobName,"Hello World")
today = datetime.datetime.utcnow()
todayPlusMonth = today + datetime.timedelta(30)
todayPlusMonthISO = todayPlusMonth.isoformat()
sasToken = blob_service.generate_shared_access_signature(containerName, None,SharedAccessPolicy(AccessPolicy(None, todayPlusMonthISO, "rw"), None))
url = "https://" + azureStorageAccountName + ".blob.core.windows.net/" + containerName + "/" + blobName + "?" + sasToken
print(url)

有什么想法可以解决这个问题吗?谢谢!

最佳答案

isoformat 方法将微秒附加到字符串中,AFAICT 这在 ISO8601 中无效。

如果您像这样修改代码:

todayPlusMonthISO = todayPlusMonth.replace(microsecond=0).isoformat() + 'Z'

生成的字符串变得有效。

例如,在您之前:

2016-01-03T21:04:10.545430

更改会将其转换为有效的:

2016-01-03T21:04:10Z

关于python - 如何使用 Azure Python SDK 为容器创建共享访问签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34475014/

相关文章:

python - 如何在 scipy 中以 cgs 单位获取物理常数?

python - 重新索引此轮类时间表的有效 Pandas 方法是什么?

c# - 如何从Azure Blob存储中的Hadoop AvroContainer删除记录?

azure - 使用 ansible 获取虚拟机事实

azure - 如何修复: The role binaries in your package are using an older version of the Windows Azure SDK

java - 无法解析配置 ':app:_debugApkCopy' 的所有依赖项

php - PayPal PHP API,信用卡和借记卡的处理方式相同吗?

python - 如何使用pytest忽略测试中的警告?

python - 如何使用 SQLAlchemy 处理两阶段提交

ios - 网络电话应用 ios8 : is pushkit still best practice?