File upload is a common requirement for web applications. In Python, the HTTPX library has made HTTP client interactions, including file upload, async-compatible and user-friendly. This tutorial covers how to upload single and multiple files using the HTTPX library.
Table of Contents
- Setup and Installation
- Uploading a Single File
- Uploading Multiple Files
- Error Handling
- Summary and Conclusion
- References
Setup and Installation
First, ensure that HTTPX is installed by running:
pip install httpx
Uploading a Single File
To upload a single file, we’ll need to open the file in binary mode and include it in the POST request through a multipart form.
import httpx
files = {'file': open('example.txt', 'rb')}
response = httpx.post('https://example.com/upload', files=files)
print(response.status_code)
Here is the breakdown of each line:
import httpx: This line imports thehttpxlibrary, which is a modern, user-friendly HTTP client for Python. It’s commonly used for making HTTP requests.files = {'file': open('example.txt', 'rb')}: This line creates a dictionary calledfiles. In this dictionary, there’s a key-value pair where the key is'file', and the value is the file object obtained by opening the file named'example.txt'in binary read mode ('rb'). This file object represents the file that will be uploaded.response = httpx.post('https://example.com/upload', files=files): This line sends an HTTP POST request to the URL'https://example.com/upload'. Thefilesparameter is used to specify the files to be uploaded. In this case, it’s passing thefilesdictionary we created earlier, which contains the file to upload. Thehttpx.post()function returns a response object representing the server’s response, including status code, headers, and response content.print(response.status_code): This line prints the status code of the response received from the server. The status code indicates the success or failure of the request. For example,200typically means the request was successful, while404means the requested resource was not found.
Uploading Multiple Files
For multiple files, the approach is quite similar, but we pass a list of file tuples to handle multiple files.
import httpx
files = [('file', open('example1.txt', 'rb')), ('file', open('example2.jpg', 'rb'))]
response = httpx.post('https://example.com/upload/multiple', files=files)
print(response.status_code)
Error Handling
It’s important to handle potential errors that could arise. Here’s a basic example of error handling:
try:
response = httpx.post('https://example.com/upload', files=files)
response.raise_for_status()
except httpx.HTTPError as error:
print(f'An error occurred: {error}')
Summary and Conclusion
We’ve learned how to use the HTTPX library for file uploads in Python. Remember to handle files responsibly and always close them after processing to prevent potential resource leaks.
References
