python-3.x - Azure 文件服务 "PUT Range"REST API 'InvalidHeaderValue' 错误

标签 python-3.x azure azure-storage

我正在尝试使用 REST API 将文件上传到 Azure 文件服务。创建文件后,“放置范围”请求失败并显示“InvalidHeaderValue”

到目前为止,我已经使用此处找到的文档成功创建了该文件。 https://learn.microsoft.com/en-us/rest/api/storageservices/create-file

之后,我尝试按照此处找到的文档将内容放入新创建的文件中。 https://learn.microsoft.com/en-us/rest/api/storageservices/put-range

这是我正在使用的 URI 的示例。它在文档中的示例旁边看起来是正确的。

uri = 'https://<account>.file.core.windows.net/<share>/<directory>/<file>?comp=range&<sas token>'

我通过...获取文件的内容

with open(file.txt, mode='rb') as fh:
    data = fh.read()

我的标题看起来像这样...

headers = {
    'x-ms-write':'update',
    'x-ms-date':'Wed, 10  Apr 2019 22:14:17 GMT',
    'x-ms-version':'2018-03-28',
    'x-ms-range':'bytes=0-' + str(len(data)),
    'Content-Length':str(len(data) + 1)
}

请求...

requests.put(url, headers=headers, data=data)

我得到的响应代码是 400,返回 header 是这样的...

{
'Content-Length': '322', 
'Content-Type': 'application/xml', 
'Server': 'Windows-Azure-File/1.0 Microsoft-HTTPAPI/2.0', 
'x-ms-request-id': '23642a26-e01a-0049-35da-ef0109000000', 
'x-ms-version': '2018-03-28', 
'x-ms-error-code': 'InvalidHeaderValue', 
'Date': 'Wed, 10 Apr 2019 20:14:46 GMT'
}

感谢您提前提供帮助。

最佳答案

该错误是由于 x-ms-rangeContent-Length 值不正确造成的。

正确的应该如下所示:

headers={
    #other headers
    'x-ms-range':'bytes=0-' + str(len(data)-1),
    'Content-Length':str(len(data))    
}

我的示例代码如下,并且工作正常:

import requests

uri = r'https://xxx.file.core.windows.net/test/good222.txt?comp=range&sv=2018-03-28&ss=bfqt&srt=sco&sp=rwdlacup&se=2019-04-12T10:59:42Z&st=2019-04-12T02:59:42Z&spr=https&sig=xxxxxxxxxx'

with open("D:\\hello.txt",mode='rb') as fh:
    data = fh.read()

print(len(data))
headers={
    'x-ms-write':'update',
    'x-ms-date':'Fri, 12 Apr 2019 06:40:14 GMT',
    'x-ms-version':'2018-03-28',
    'x-ms-range':'bytes=0-' + str(len(data)-1),
    'Content-Length':str(len(data))    
}

r= requests.put(uri,data=data,headers=headers)
print(r.status_code)
print(r.headers)

结果(该文件也在 Azure 门户上更新):

enter image description here

另请注意,文件(本地)长度不应长于您要在 Azure 文件共享上更新的长度。

关于python-3.x - Azure 文件服务 "PUT Range"REST API 'InvalidHeaderValue' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621162/

相关文章:

python - 要列出的坐标 (str)

mongodb - Azure cosmosDB(mongoDB),如何在 GO lang 或通过 Shell 中禁用集合中的自动索引

javascript - 使用js生成Azure blob存储sas token

python - PyQt5:DLL加载失败:找不到指定的模块

python - 从 HTML 中提取脚本标签内的字符串

python - 获取属性错误 : 'map' object has no attribute 'sort'

asp.net - Windows Azure 表存储查询错误 - 请求输入之一无效

azure - 如何为 Azure App Insights 中的页面 View 事件提供自定义名称?

c# - Azure Batch客户端,如何测试有效性?

reactjs - 使用 React 将图像上传到 azure blob 存储