如何在Flas上使用python的qrcode服务生成的QR图像

2024-05-16 23:48:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个生成QR图像的函数:

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

现在我们的想法是产生图像,然后把它扔到烧瓶上,作为一个图像,这是我对烧瓶的功能:

^{pr2}$

但它似乎不能正常工作。。。我打了一个500的错误,所以我不太确定我做错了什么。在


Tags: 函数图像importimgmake烧瓶versiondef
2条回答

编辑:在回答后看到你关于不想保存到临时文件的评论。但是如果你决定把它保存到一个临时的位置,这里有一个方法。在

您可以将二维码图像保存在临时位置,并使用send_file为其提供服务。在

send_file记录在http://flask.pocoo.org/docs/0.10/api/#flask.send_file

我还没有测试过这个代码片段,但是类似这样的代码应该可以工作。在

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)

Google+上的一位先生为我提供了一个解决方案,虽然他没有SO账户,但我决定分享他的答案:

#!/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)

相关问题 更多 >