Send MySQL blob content as a json response
Question: I have the following code of a GET method which takes a photo which is stored
in a blob type field in MySql and return. I want to return it to the client
inside a JSON string in a type it can display the image in an angularjs
application.

    
    
     def GET(self,r):
        user_data = CC.get_data(query) # holds the content of the blob field.
        print type(user_data) # prints <type 'str'>
        data = {'name': 'test',
               'photo': user_data}
        return json.dump(data)
    

This gives,

    
    
       UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0:
       invalid start byte
    

I have found in some websites its better to send as photo as byte array. Im
using web.py python framework. whats the best way to do this?


Answer: To prevent data loss, the best thing you can do to send binary data is encode
as `base64`.

    
    
    import base64
    
    def GET(self,r):
        user_data = CC.get_data(query) # holds the content of the blob field.
        data = {'name': 'test',
               'photo': base64.b64encode(user_data)}
        return json.dump(data)
    

However, sending binary data over JSON is really not recommended, specially in
web. You can send a URL to download the photo, for example.

