python send image in post request with json data

Solutions on MaxInterview for python send image in post request with json data by the best coders in the world

showing results for - "python send image in post request with json data"
Kale
29 May 2016
1import base64
2import json                    
3
4import requests
5
6api = 'http://localhost:8080/test'
7image_file = 'sample_image.png'
8
9with open(image_file, "rb") as f:
10    im_bytes = f.read()        
11im_b64 = base64.b64encode(im_bytes).decode("utf8")
12
13headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
14  
15payload = json.dumps({"image": im_b64, "other_key": "value"})
16response = requests.post(api, data=payload, headers=headers)
17try:
18    data = response.json()     
19    print(data)                
20except requests.exceptions.RequestException:
21    print(response.text)
22