Home >Backend Development >Python Tutorial >How to Send Multipart/Form-Data Requests in Python using Requests and Requests-Toolbelt?
Requests provides the ability to send multipart/form-data requests, allowing for both file uploads and form data submission.
To upload a file, simply specify a key-value pair in the files parameter, where the key is the form field name and the value is an open file object or file path. For instance:
import requests with open('image.jpg', 'rb') as f: file_data = {'image': f} response = requests.post('http://example.com/upload', files=file_data)
To send form data, you can also use the files parameter. However, unlike file uploads, the values are not file objects but strings or bytes.
To specify form data, use a dictionary where the keys are the form field names and the values are the data you want to submit. For example:
form_data = {'username': 'myusername', 'password': 'mypassword'} response = requests.post('http://example.com/login', files=form_data)
You can simultaneously upload files and submit form data by using both the files and data parameters. If data is a string, it will be used instead of files. If data is a dictionary, it will be merged with files.
For instance:
form_data = {'comment': 'Hello, world!'} file_data = {'image': 'image.jpg'} response = requests.post('http://example.com/post', data=form_data, files=file_data)
The requests-toolbelt library provides enhanced multipart support that includes advanced features like:
To use requests-toolbelt, install it via pip install requests-toolbelt and follow these steps:
from requests_toolbelt.multipart.encoder import MultipartEncoder
mp_encoder = MultipartEncoder( fields={ 'field_name': 'field_value', ('file_name', 'file_content', 'file_type'), # Other form data fields and files can be added here } )
headers = {'Content-Type': mp_encoder.content_type} response = requests.post('http://example.com/post', data=mp_encoder, headers=headers)
By utilizing these methods, you can seamlessly send multipart/form-data requests in Python for both file uploads and form data submission.
The above is the detailed content of How to Send Multipart/Form-Data Requests in Python using Requests and Requests-Toolbelt?. For more information, please follow other related articles on the PHP Chinese website!