1

So I have this code that send API request to upload a file to a server, after searching the web I came up with something like that where 'payload' is additional params I need to send and 'files' is a path to the file I want to upload :

def sendAPIRequest2(self, env, object, method, params, files):
    apiPath = "/api/secure/jsonws"
    headers = {'content-type': 'multipart/form-data'}
    url = env + apiPath + object
    payload = {
        "method": method,
        "params": params,
        "jsonrpc": "2.0"
    }
    data = json.dumps(payload)
    myFile = {'file': open(files,'rb')}
    try:
        r = requests.post(url, files=myFile, data=data, headers=headers, 
                auth=HTTPBasicAuth(self.user, self.password), verify=False)
        print r.text
        resjson = json.loads(r.text)
    except:
        print "no Valid JSON has returned from"+object+" API"
        sys.exit(1)
    return resjson

I get:

ValueError: Data must not be a string.

What am I doing wrong?

Itai Malek
  • 301
  • 2
  • 5
  • 14
  • always put full error message (Traceback) in question (as text, not screenshot). There are other useful informations. ie. it shows which line makes problem. – furas Dec 11 '17 at 16:45
  • 2
    Possible duplicate of [ValueError: Data must not be a string](https://stackoverflow.com/questions/27553082/valueerror-data-must-not-be-a-string) – Marco Lavagnino Dec 11 '17 at 18:49
  • Looks like a duplicate to me but why not use r.json() instead of json.loads(r.text)? – Dan-Dev Dec 11 '17 at 22:13
  • @Dan-Dev, can you explain the difference? – Itai Malek Dec 12 '17 at 07:52
  • If there is a result r.json() will return a JSON object directly no need to get a text object and convert it to JSON. – Dan-Dev Dec 12 '17 at 10:02

0 Answers0