python requests library upload file

Python Requests Library Upload File

If you want to upload a file to a web server using Python, the requests library is a great tool to use.

Using the requests.post() method

To upload a file using requests, you can use the post() method and provide it with the URL of the server you want to upload the file to. You also need to provide the file you want to upload as an argument:


import requests

url = 'https://example.com/upload'
files = {'file': open('path/to/file', 'rb')}

response = requests.post(url, files=files)

The 'files' argument should be a dictionary where the key is the name of the file input field in the HTML form, and the value is a file object. In this example, we are opening the file in binary mode and passing it to the post() method.

Using the multipart/form-data Content-Type

When uploading a file using requests, you need to use the 'multipart/form-data' Content-Type. This allows you to include binary data (the file) in your request, along with other form data if needed.

If you are using the post() method, requests will automatically set the Content-Type to 'multipart/form-data' for you when you pass in the 'files' argument.

Handling errors

If there are any errors during the upload process, requests will raise an exception. You can catch this exception and handle it as needed:


try:
    response = requests.post(url, files=files)
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(e.response.status_code, e.response.text)

In this example, we are using the raise_for_status() method to raise an exception if the HTTP status code is an error (4xx or 5xx).

Conclusion

The requests library makes it easy to upload files to a web server using Python. By following the examples above, you can upload files using the post() method and handle any errors that may occur.