How to serve generated QR image using python qrcode on 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 an image and then drop it on the bulb to serve as the image, this is my function for the bulb:

 @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 looks like it is working fine ... I find a 500 error, so I'm not quite sure what I'm doing wrong.

+5
source share
2 answers

The gentleman from Google+ provided me with a solution, although he does not have an SO account, I decided to share my answer:

 #!/usr/bin/env python2.7 # -*- coding: utf-8 -*- """Example of Flask and qrcode. NOTE: by requirements image in memory! """ __author__ = 'Daniel Leybovich < setarckos@gmail.com >' __version__ = (0, 0, 1) import os import sys import flask import qrcode import cStringIO app = flask.Flask(__name__) def random_qr(url='www.google.com'): qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4) qr.add_data(url) qr.make(fit=True) img = qr.make_image() return img @app.route('/get_qrimg') def get_qrimg(): img_buf = cStringIO.StringIO() img = random_qr(url='www.python.org') img.save(img_buf) img_buf.seek(0) return flask.send_file(img_buf, mimetype='image/png') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) 
0
source

EDIT: You have a comment about what you do not want to save to a temporary file after the response. But if you decide to save it in a temporary place, here is the way.

You can save the QR code image in a temporary place and execute it using send_file .

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

I have not tested this piece of code, 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) 
+1
source

Source: https://habr.com/ru/post/1204889/


All Articles