如何使用Azure Python SDK

时间:2015-12-26 20:33:39

标签: python azure sdk azure-storage azure-storage-blobs

我正在尝试使用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>
&#13;
&#13;
&#13;

似乎问题必须出在这行代码中:

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)

任何想法如何解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:3)

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

如果您修改代码如下:

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

生成的字符串变为有效。

例如,在你有:

之前
  

2016-01-03T21:04:10.545430

更改会将其转换为有效:

  

2016-01-03T21:04:10Z