Question: How can I send multipart form data in Python using the requests library? While I understand how to attach files, I'm struggling to incorporate standard form data into such requests.
Answer:
Requests automatically handles multipart form data when a files parameter is specified, resulting in a multipart/form-data POST request instead of an application/x-www-form-urlencoded POST.
Syntax:
from requests import post response = post( url, files={ "form_field_name": "form_field_value", # No quotes needed for non-string values } )
Example:
response = post("http://httpbin.org/post", files={"foo": "bar"}) assert response.status_code == 200
Advanced Control:
Use tuples to customize the filename, content type, and additional headers for each part. Tuple components include:
Example:
files = {"foo": (None, "bar")} # No filename specified
Ordered Multiple Fields:
Use a list of tuples for ordered or multiple fields with the same name.
Handling Data and Files:
When using both data and files, a string data parameter will take precedence. Otherwise, both data and files are combined in the request.
Optional Libraries:
The requests-toolbelt project provides advanced Multipart support, allowing for:
Example with requests-toolbelt:
import MultipartEncoder from requests_toolbelt fields = { "foo": b"bar", # Fields support bytes objects "spam": ("spam.txt", open("spam.txt", "rb"), "text/plain") # Stream files } mp_encoder = MultipartEncoder(fields) response = post( url, data=mp_encoder, headers={"Content-Type": mp_encoder.content_type} )
Note: For the requests-toolbelt method, do not use files= argument as the MultipartEncoder is posted as the data payload.
The above is the detailed content of How to Send Multipart Form Data with Files and Standard Form Data in Python?. For more information, please follow other related articles on the PHP Chinese website!