I have a problem trying to upload a file via multipart/form-data. The problem is not with requests/toolbelt but the API I am working with (is an API that mainly uses requests for a particular platform called Mercado Libre, similar to Ebay).
I’m posting the relevant code:
The particular method of the API:
def post(self, path, body=None, params=None, extra_headers=None):
params = params or {}
headers = {'Accept': 'application/json', 'User-Agent':self.SDK_VERSION, 'Content-type':'application/json'}
if extra_headers:
headers.update(extra_headers)
uri = self.make_path(path)
if body:
body = json.dumps(body)
response = self._requests.post(uri, data=body, params=urlencode(params), headers=headers)
return response
My code:
from requests_toolbelt import MultipartEncoder
encoder = MultipartEncoder(
fields={
'file': (
'myfile.txt',
open('/tmp/myfile.txt', 'rb'),
'text/plain'
)
}
)
self.post(path='the-url-path', body=encoder, extra_headers={'Content-type': encoder.content_type})
Of course this wil gives an error because the method line: body = json.dumps(body):
TypeError: Object of type ‘MultipartEncoder’ is not JSON serializable
What I am doing wrong or how I can fix this?
Thanks in advance.
3
Answers
For now, I just implemented the solution using pycurl as @kcorlidy suggested till developers of that API write the right way to do it with requests. So, I've added an alternative method to the API to upload multipart/form-data files (also a utility class to return response similar to requests):
Thanks @kcorlidy for the support!
You need to operate with the file a little bit differently, by using the
with
keyword:I imitate the request from curl. But i did not have account in Mercado Libre, therefore i can not promise script is correct. However, if example on upload file document in right that this script should run successfully.