【发布时间】:2018-05-30 20:02:22
【问题描述】:
我正在尝试将 Blob (pdf) 文件从我的笔记本电脑上传到 Azure 存储帐户中的容器。我发现它工作正常,但有一个小故障。
我正在使用以下方法计算文件大小:
f_info = os.stat(file_path)
file_size = (f_info.st_size) # returns - 19337
然后我在下面的规范化标题中插入这个值:
ch = "PUT\n\n\n"+str(file_size)+"\n\napplication/pdf\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob" + "\nx-ms-date:" + date + "\nx-ms-version:" + version + "\n"
并将 PUT 请求发送到 PUT Blob API,但是,它返回错误消息,“身份验证失败,因为服务器使用以下字符串来计算签名”
\'PUT\n\n\n19497\n\n应用程序/pdf\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx -ms-date:[日期]\nx-ms-version:[API 版本]
查看此字符串,很明显身份验证失败,因为 azure 计算的文件大小返回不同的值!我不明白它是如何计算这个文件大小的值的?!?!
仅供参考:如果我在规范化字符串中将 19337 替换为 19497 并重新运行。有用! 关于我在哪里犯错的任何建议?
下面是代码:
storage_AccountName = '<storage account name>'
storage_ContainerName = "<container_name>"
storageKey='<key>'
fd = "C:\\<path>\\<to>\\<file_to_upload>.pdf"
URI = 'https://' + storageAccountName + '.blob.core.windows.net/<storage_ContainerName >/<blob_file_name.pdf>
version = '2017-07-29'
date = datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT")
if os.path.isfile(fd):
file_info = os.stat(fd)
file_size = (file_info.st_size)
ch = "PUT\n\n\n"+str(file_size)+"\n\napplication/pdf\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob" + "\nx-ms-date:" + date + "\nx-ms-version:" + version + "\n"
cr = "/<storage_AccountName>/<storage_Containername>/<blob_file_name.pdf>"
canonicalizedString = ch + cr
storage_account_key = base64.b64decode(storageKey)
byte_canonicalizedString=canonicalizedString.encode('utf-8')
signature = base64.b64encode(hmac.new(key=storage_account_key, msg=byte_canonicalizedString, digestmod=hashlib.sha256).digest())
header = {
'x-ms-blob-type': "BlockBlob",
'x-ms-date': date,
'x-ms-version': version,
'Authorization': 'SharedKey ' + storageAccountName + ':' + signature.decode('utf-8'),
#'Content-Length': str(19497), # works
'Content-Length': str(file_size), # doesn't work
'Content-Type': "application/pdf"}
files = {'file': open(fd, 'rb')}
result = requests.put(url = URI, headers = header, files = files)
print (result.content)
【问题讨论】:
-
你可以试试
os.path.getsize(file_path)吗? -
嗨 Gaurav,也试过了,结果都是相同的值,即 19337
-
可以分享完整的代码吗?
-
下面是代码:
-
在 Python 上工作不多,但我认为问题在于您没有上传文件内容。相反,您正在上传一个包含文件内容的对象,因此内容长度正在增加。您可以更改以下代码行:
files = {'file': open(fd, 'rb')} result = requests.put(url = URI, headers = header, files = files)类似于:data = open(fd, 'rb') as stream result = requests.put(url = URI, headers = header, data = data)。 HTH。
标签: python-3.x rest azure