Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve a generated QR Image using python's qrcode on Flask

Tags:

python

flask

I have a function that generates a QR Image:

import qrcode
def generateRandomQR():
    qr = qrcode.QRCode(version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
            )

    qr.add_data("Huehue")
    qr.make(fit=True)
    img = qr.make_image()
    return img

now then the idea is to generate the image, and then throw it on flask, to serve as an image, this is my function for flask:

@app.route("/qrgenerator/image.jpg")
def generateQRImage():
    response = make_response(qrWrapper.generateRandomQR())
    response.headers["Content-Type"] = "image/jpeg"
    response.headers["Content-Disposition"] = "attachment; filename=image.jpg"
    return response

But it doesn't seem like it's working properly... I'm hitting a 500 error, so I'm not quite sure what I'm dong wrong.

like image 243
Stupid.Fat.Cat Avatar asked Oct 17 '14 03:10

Stupid.Fat.Cat


1 Answers

EDIT: Saw your comment about not wanting to save to a temporary file after answering. But if you decide to save it to a temporary location, here is a way.

You can save the QR code image in a temporary location and serve it using send_file.

send_file is documented in http://flask.pocoo.org/docs/0.10/api/#flask.send_file

I haven't tested this code snippet, but something like this should work.

from flask import send_file

@app.route("/qrgenerator/image.jpg")
def generateQRImage():
    response = make_response(qrWrapper.generateRandomQR())

    temp_location = '/tmp/image.jpg'

    # Save the qr image in a temp location
    image_file = open(temp_location, 'wb')
    image_file.write(response)
    image_file.close

    # Construct response now
    response.headers["Content-Type"] = "image/jpeg"
    response.headers["Content-Disposition"] = "attachment; filename=image.jpg"
    return send_file(temp_location)
like image 122
Phalgun Avatar answered Sep 22 '22 15:09

Phalgun