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.
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)
A gentleman on Google+ has provided me a solution, although he has no SO account, I've decided to share his 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.