[파이썬] requests Multipart 인코딩 데이터 전송

When working with APIs or sending data via HTTP requests, there might be cases where you need to send multipart-encoded data. This type of encoding allows you to combine different types of data such as text, files, or images into a single HTTP request payload.

In Python, the requests library provides an easy way to send multipart-encoded data. In this blog post, we will explore how to use the requests library to send multipart data, including text and files, in Python.

Installation

Before we start, make sure you have the requests library installed. You can install it using pip:

pip install requests

Once the installation is complete, you can import the requests module in your Python script or interactive session.

Sending Multipart Data

To send multipart data using the requests library, we need to use the multipart/form-data content type and create a multipart_encoder object from the requests_toolbelt module.

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

# Create the multipart encoder object
multipart_data = MultipartEncoder(
    fields={
        'field1': 'value1',
        'field2': 'value2',
        'file': ('filename.txt', open('path/to/file.txt', 'rb'), 'text/plain')
    }
)

# Set the headers
headers = {'Content-Type': multipart_data.content_type}

# Send the request
response = requests.post('https://example.com/upload', data=multipart_data, headers=headers)

# Print the response
print(response.text)

In the example above, we create a multipart_data object using the MultipartEncoder class and set the fields we want to include in the request. The fields parameter is a dictionary where we can specify text fields as key-value pairs and files as (filename, file_object, content_type) tuples.

We also set the appropriate Content-Type header to indicate that we are sending multipart data.

Finally, we send the POST request using the requests.post method, passing the multipart_data object as the data parameter and the headers dictionary containing the Content-Type header.

Conclusion

In this blog post, we have seen how to send multipart-encoded data using the requests library in Python. Sending multipart data is essential when working with APIs that expect this type of data format.

By utilizing the requests_toolbelt module and the MultipartEncoder class, we can easily create the necessary multipart data and send it via the requests.post method.

I hope you found this blog post helpful. Feel free to explore the requests documentation for more details on sending other types of data using this powerful Python library.