1

I am getting a json array which contains bytes of an image. This json array in embedded in json object. When checking the type of elements in this json array it is showing class 'str'.

I want to save this bytes from the json array to distinct files. This is what i have done.

images = []
            images = data["Images"]
            del data["Images"]
            future = db.Document.insert(data)
            result = yield future

            if result:
                index = 1
                for image in images:
                    os.mkdir("/home/sandeep/Projects/PycharmProjects/Fortentia/src/Images/QID"+str(result))
                    f = open("/home/sandeep/Projects/PycharmProjects/Fortentia/src/Images/QID"+str(result)+"option"+str(index)+".jpg","wb")
                    f.write(image)
                    f.close()
                    index += 1
                self.write("successful")
            else:
                self.write("Unsuccessful")  

I am using tornado with Motor for this.

The error I am getting is:

[E 160209 20:27:17 web:1524] Uncaught exception POST /question (192.168.0.103)
    HTTPServerRequest(protocol='http', host='192.168.0.2:8000', method='POST', uri='/question', version='HTTP/1.1', remote_ip='192.168.0.103', headers={'Accept-Encoding': 'gzip', 'Content-Type': 'application/json; charset=utf-8', 'Host': '192.168.0.2:8000', 'Connection': 'Keep-Alive', 'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1; Google Nexus 4 - 5.1.0 - API 22 - 768x1280 Build/LMY47D)', 'Content-Length': '206'})
    Traceback (most recent call last):
      File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 1445, in _execute
        result = yield result
      File "/usr/local/lib/python3.4/dist-packages/tornado/gen.py", line 1008, in run
        value = future.result()
      File "/usr/local/lib/python3.4/dist-packages/tornado/concurrent.py", line 232, in result
        raise_exc_info(self._exc_info)
      File "<string>", line 3, in raise_exc_info
      File "/usr/local/lib/python3.4/dist-packages/tornado/gen.py", line 1017, in run
        yielded = self.gen.send(value)
      File "/home/sandeep/Projects/PycharmProjects/Fortentia/src/Question.py", line 32, in post
        f.write(image)
    TypeError: 'str' does not support the buffer interface

Thanks in advance.

  • Check this post: http://stackoverflow.com/questions/18367007/python-how-to-write-to-a-binary-file – msuberri Feb 09 '16 at 16:11
  • @msuberri we tried that also but then it is showing error "TypeError: string argument without an encoding". When we specify UTF-8 as encoding then also an error is generated. Thing is our client is sending array of bye but what data type here in python we are seeing is str why so? – Gaurav Jindal Feb 10 '16 at 15:00

0 Answers0