ValueError: data must not be a string

I am trying to do the following with requests

:

data = {'hello', 'goodbye'}
json_data = json.dumps(data)
headers = {
        'Access-Key': self.api_key,
        'Access-Signature': signature,
        'Access-Nonce': nonce,
        'Content-Type': 'application/json',
        'Accept': 'text/plain'
    }
r = requests.post(url, headers=headers, data=json_data, 
                 files={'file': open('/Users/david/Desktop/a.png', 'rb')})

      

However, I am getting the following error:

ValueError: Data must not be a string.

      

Note that if I remove the parameter files

it works as needed. Why requests

won't it let me send a json-encoded string for data if enabled files

?

Note that if I modify data

as a normal normal python dictionary (not a json-encoded string) this works. It looks like the problem is that if the files are not json encoded then the data cannot be json-encoded. However, I need my data to be encoded according to the hash signature generated by the API.

+4


source to share


4 answers


When you point your body to a JSON string, you can no longer attach the file as the MIME type is required to upload the file multipart/form-data

.

You have two options:



  • Encapsulate JSON string as part of form data (something like json => json.dumps(data)

    )
  • Base64 encode your file and pass it in the JSON request body. This one looks like a lot of work .
+4


source


An alternative solution to this problem is to publish the data as a file.



0


source


same problem, do you have a code?

0


source


removing the following worked for me in my case:

'Content-Type': 'application/json'

      

then the data should be transferred as a dictionary

0


source







All Articles