2

Using the Python3 requests module and the PUT Blob Azure Rest API to upload a file into Azure storage:

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}")

This works for files with content. But, when trying to upload an empty file I get a 400 response code. How can I upload an empty file?

1 Answers1

1

If you want to upload an empty file, you should remove the data=data in the requests.put() method.

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**")

And also, you can conditionally use requests.put() method with/without data=data. First, in your code, check the length of the file, if it's zero, you can use requests.put() method without data=data; and if the length is larger than zero, use the requests.put() method with data=data.

Hope it can helps.

Ivan Glasenberg
  • 29,865
  • 2
  • 44
  • 60