I am trying to do the following with requests
:
JavaScript
x
12
12
1
data = {'hello', 'goodbye'}
2
json_data = json.dumps(data)
3
headers = {
4
'Access-Key': self.api_key,
5
'Access-Signature': signature,
6
'Access-Nonce': nonce,
7
'Content-Type': 'application/json',
8
'Accept': 'text/plain'
9
}
10
r = requests.post(url, headers=headers, data=json_data,
11
files={'file': open('/Users/david/Desktop/a.png', 'rb')})
12
However, I get the following error:
JavaScript
1
2
1
ValueError: Data must not be a string.
2
Note that if I remove the files
parameter, it works as needed. Why won’t requests
allow me to send a json-encoded string for data if files
is included?
Note that if I change data
to be just the normal python dictionary (and not a json-encoded string), the above works. So it seems that the issue is that if files is not json-encoded, then data cannot be json-encoded. However, I need to have my data encoded to match a hash signature that’s being created by the API.
Advertisement
Answer
When you specify your body to a JSON string, you can no longer attach a file since file uploading requires the MIME type multipart/form-data
.
You have two options:
- Encapsulate your JSON string as part as the form data (something like
json => json.dumps(data)
) - Encode your file in Base64 and transmit it in the JSON request body. This looks like a lot of work though.