Search code examples
postgresqlpython-3.xsqlalchemycherrypy

How to return a bytes value in a cherry py request body


I have a postgres table that contains a bytea column. This column contains an image.

The SqlAlchemy model has this column defined as a LargeBinary. I've also tried to using BLOB, but It didn't change a thing.

I can easily retrieve a value from the database and what I get is a variable of type bytes.

How can I jsonify that bytes array? I need the json value so I can return it in the cherrypy request body like so :

data = { 'id_image': image.id_image, 'image': image.value }

Solution

  • I'm assuming you need to show that image in a browser or similar software.

    Normally you can use Data URI when embedding image as a string into a web page. Modern browsers know how to decode it back.

    Also I'm assuming you have a PNG image. If your case is different, feel free to change image/png to something, which matches your needs.

    Here's how you can generate data URI using Python.

    This example uses Python 3.6 syntax:

    import base64
    
    img_id = image.id_image
    img_base64_encoded = base64.b64encode(image.value).decode('ascii')
    img_type = 'image/png'  # Use some smart image type guessing if applicable
    
    img_data_uri = f'data:{img_type};base64,{img_base64_encoded}'
    
    img_data = {
        'id': image.id_image,
        'data_uri': img_data_uri
    }