Python3 请求模块 PUT 空文件
Python3 requests module PUT empty file
使用 Python3 请求模块和 PUT Blob Azure Rest API 将文件上传到 Azure 存储:
file_name = "testfile.txt"
url = f"https://<storageaccount>.blob.core.windows.net/test/{file_name}?sv=<SASTOKEN>"
with open(file_name, 'rb') as data:
headers = {
'x-ms-version': '2019-02-02',
'x-ms-date': 'Mon, 30 Mar 2020 17:20:00 GMT',
'x-ms-blob-type': 'BlockBlob',
'x-ms-access-tier': 'Cool'
}
response = requests.put(
url,
data=data,
headers=headers
)
print(f"Response {response}")
这适用于包含内容的文件。但是,当尝试上传一个空文件时,我得到一个 400
响应代码。如何上传空文件?
如果要上传空文件,应删除requests.put()
方法中的data=data
。
print("**begin**")
with open(file_name,'rb') as data:
headers = {
'x-ms-version': '2019-02-02',
'x-ms-date': 'Fri, 03 Apr 2020 07:16:17 GMT',
'x-ms-blob-type': 'BlockBlob',
'x-ms-access-tier': 'Cool'
}
response = requests.put(
url,
headers=headers
)
print(response.status_code)
print(response.content)
print("**done**")
此外,您还可以有条件地使用requests.put()
方法with/withoutdata=data
。首先,在你的代码中,检查文件的长度,如果它是零,你可以使用 requests.put()
方法而不使用 data=data
;如果长度大于零,则使用 requests.put()
方法和 data=data
.
希望对您有所帮助。
使用 Python3 请求模块和 PUT Blob Azure Rest API 将文件上传到 Azure 存储:
file_name = "testfile.txt"
url = f"https://<storageaccount>.blob.core.windows.net/test/{file_name}?sv=<SASTOKEN>"
with open(file_name, 'rb') as data:
headers = {
'x-ms-version': '2019-02-02',
'x-ms-date': 'Mon, 30 Mar 2020 17:20:00 GMT',
'x-ms-blob-type': 'BlockBlob',
'x-ms-access-tier': 'Cool'
}
response = requests.put(
url,
data=data,
headers=headers
)
print(f"Response {response}")
这适用于包含内容的文件。但是,当尝试上传一个空文件时,我得到一个 400
响应代码。如何上传空文件?
如果要上传空文件,应删除requests.put()
方法中的data=data
。
print("**begin**")
with open(file_name,'rb') as data:
headers = {
'x-ms-version': '2019-02-02',
'x-ms-date': 'Fri, 03 Apr 2020 07:16:17 GMT',
'x-ms-blob-type': 'BlockBlob',
'x-ms-access-tier': 'Cool'
}
response = requests.put(
url,
headers=headers
)
print(response.status_code)
print(response.content)
print("**done**")
此外,您还可以有条件地使用requests.put()
方法with/withoutdata=data
。首先,在你的代码中,检查文件的长度,如果它是零,你可以使用 requests.put()
方法而不使用 data=data
;如果长度大于零,则使用 requests.put()
方法和 data=data
.
希望对您有所帮助。