K
K
kenik2014-04-08 12:41:33
Flask
kenik, 2014-04-08 12:41:33

Python + Flask, output image from MySQL database?

I have a database that stores images in a BLOB field. I'm trying to display them in the browser. Site on Flask.

In PHP, it was solved with a script like this:

$img=mysql_query("SELECT `emblem_len`, `emblem_data` FROM `icons` WHERE `icon_id` = $id"); 

$img_row = mysql_fetch_array($img);
Header("Content-Disposition: inline; filename=".$id.".png");
Header("Content-type: image/png");
Header("Content-length: ".(int)$img_row["emblem_len"]);
echo $img_row["emblem_data"];

Now I got something like this:
@app.route("/show_icon/<int:pid>.png")
def show_icon(pid):
        db = pydb.get_db()
        cursor = db.cursor()
        sql = "SELECT `emblem_data`, `emblem_len` FROM `icons` WHERE `icon_id` = %s;"
        cur = cursor.execute(sql % (pid))
        image = cursor.fetchone()
        resp = make_response(image[0])
        resp.headers['Content-Type'] = 'image/png'
        resp.headers['Content-Length'] = image[1]
        resp.headers['Content-Disposition'] =  'inline; filename="%s.png"' % (pid)
        return resp

The text of the field is displayed, the headers are sent, but the picture is not shown.

PS The question is not about where it is better to store pictures. Pictures are stored in the database independently of me, I need to display them in the browser.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ellinium, 2014-05-09
@Ellinium

image.decode('base64')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question