user852566
user852566

Reputation: 181

Issue sending base64 image to Rest web service from Raspberry Pi

I am having a problem sending a image to a rest service. I know the service is working as I have sent a test string ("test string") to the service, you can see the results in the shell info below. I converted the image to Base64 then tried to send it to the service and am getting a Type Error. I am using Python Requests and base64 libraries. Below is showing the successful call and the one that is failing. I shortened the base64 string for readability.

Thank you for any help...

Python 3.4.2 (default, Oct 19 2014, 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Gpio pin 25 is HIGH
file name = /home/pi/photo/2016-01-06_17.59.31.jpg
{'Content-Type': 'application/json', 'Content-Length': '141',
'User-Agent': 'python-requests/2.4.3 CPython/3.4.2 Linux/4.1.13+',
'Accept': 'text/plain', 'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive'}
"Success"
https://alerts4yousvc.azurewebsites.net/api/SendReading
200
Gpio pin 25 is LOW

>>> ================================ RESTART ================================
>>>
Gpio pin 25 is HIGH
file name = /home/pi/photo/2016-01-06_18.00.32.jpg
Traceback (most recent call last):
  File "/home/pi/Source/motionpi_http5.py", line 45, in <module>
    r = requests.post("https://alerts4yousvc.azurewebsites.net/api/SendReading",
json=payload, headers=headers)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 94, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/api.py", line 49, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line
443, in request
    prep = self.prepare_request(req)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line
374, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/usr/lib/python3/dist-packages/requests/models.py", line 307, in prepare
    self.prepare_body(data, files, json)
  File "/usr/lib/python3/dist-packages/requests/models.py", line 424,
in prepare_body
    body = json_dumps(json)
  File "/usr/lib/python3.4/json/__init__.py", line 230, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.4/json/encoder.py", line 192, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.4/json/encoder.py", line 250, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.4/json/encoder.py", line 173, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'/9j/4WQGRXhpZgAATU0AKgAAAAgACgEAAAQAAAABAAABQAEBAAQAAAABAAAA8AEPAAIAAAAMAAAAhgEQAAIAAAAKAAAAkgEaAAUAAAABAAAAnAEbAAUAAAABAAAApAEoAAMAAAABAAIAAAEyAAIAAAAUAAAArAITAAMAAAABAAEAAIdpAAQAAAABAAAAwAAAA4hSYXNwYmVycnlQaQBSUF9PVjU2NDcAAAAASAAAAAEAAABIAAAAATIwMTY6MDE6MDYgMTg6MDA6MzIAABeCmgAFAAAAAQAAAdqCnQAFAAAAAQAAAeKIIgADAAAAAQADAACIJwADAAAAAQD6AACQAAAHAAAABDAyMjCQAwACAAAAFAAAAeqQBAACAAAAFAAAAf6RAQAHAAAABAECAwCSAQAKAAAAAQAAAhKSAgAFAAAAAQAAAhqSAwAKAAAAAQAAAiKSBQAFAAAAAQAAAiqSBwADAAAAAQACAACSCQADAAAAAQAAAACSCgAFAAAAAQAAAjKSfAAHAAABPAAAAjqgAAAHAAAABDAxMDCgAQADAAAAAQABAACgAgAEAAAAAQAAAUCgAwAEAAAAAQAAAPCgBQAEAAAAAQAAA3akAgADAAAAAQAAAACkAwADAAAAAQAAAAAAAAAAAAHoPgAPQkAAAHE4AAAnEDIwMTY6MDE6MDYgMTg6MDA6MzIAMjAxNjowMTowNiAxODowMDozMgAALcczAA9CQAAAd/EAACcQAAAAAwAAAGQAAHfxAAAnEAAAjIgAACcQZXY9LTEgbWx1IyxD/AP/Z'
is not JSON serializable

This is the code that i am using...

import RPi.GPIO as GPIO
import time
import picamera
import datetime
import base64
import requests
import urllib
import json

def get_file_name():
    return datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.jpg")

sensor = 25

GPIO.setmode(GPIO.BCM)
GPIO.setup(sensor,GPIO.IN,GPIO.PUD_DOWN)

previous_state = True
current_state = False
client_key="79c538c0f239"
task_key="ece0e81a26f1"


cam = picamera.PiCamera()
cam.resolution =(320,240)

while True:
    time.sleep(1)   
    previous_state = current_state   
    current_state = GPIO.input(sensor)
   # print("previous_state %s" %(previous_state))
   # print("current_state %s" %(current_state))
    if current_state != previous_state:
      #  print("4")
        new_state = "HIGH" if current_state else "LOW"
        print("Gpio pin %s is %s" % (sensor, new_state))
        if current_state:
            fileName = get_file_name()
            imgpath = "/home/pi/photo/" + fileName
            print("file name = %s" % (imgpath))
            cam.capture(imgpath)
            image_64 = base64.b64encode(open(imgpath,"rb").read())
            payload = {"ClientKey": client_key,"TaskId": task_key, "MsgBody":image_64, "Reading":1}
            headers = {'Content-Type': 'application/json', 'Accept':'text/plain'}
            r = requests.post("https://alerts4yousvc.azurewebsites.net/api/SendReading", json=payload, headers=headers)
            print(r.request.headers)
            print(r.text)
            print(r.url)
            print(r.status_code)

Upvotes: 1

Views: 1668

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114038

I guess you could probably do

 image_64 = str(base64.b64encode(open(imgpath,"rb").read()).decode("ascii"))

Upvotes: 4

Related Questions