Skip to content
Advertisement

Flask unable to send image back in json response

Attempting to send an image to the client browser – the following code works perfectly – please assume that I am receiving the correct base64.b64encoded byte stream:

def get_user_image(usr_rec):   
    with open("config.json",) as config:        
        data = json.load(config)            
        avatar = data["PATHS"]["AVATAR"]        
        file_ext = os.path.splitext(usrdata["avatar"])[1] if usrdata["avatar"] else ".png"                    
        file_fmt = ".jpeg" if file_ext.upper()==".JPG" else file_ext                   
        path = "{}/{}{}".format(avatar,usr_rec["recordid"],file_ext)            
        img = Image.open(path,mode="r")    
        barr = io.BytesIO()
        img.save(barr,format="{}".format(file_fmt[1:].upper()))
        return b64encode(barr.getvalue())


def format_record (usr_rec):
    avatar = get_user_image(usr_rec["recordid"])
    return jsonify({"avatar": str(avatar)})

On my development box. Move it to a flask production running under gunicorn and I get JSON serialization errors: TypeError: Object of type bytes is not JSON serializable I am also getting this error for Decimal types as well.

How can I get around this issue?

Advertisement

Answer

This is because your get_user_image function returns a stream of bytes and not a string, so you have to cast the bytes read into a string: get_user_image(usr_rec["recordid"]).decode("utf-8"). The same happens for the object of type Decimal.

The jsonify function only serializes objects of type string, as you can also see here and here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement