【Django】生成二维码

qrcode是一个生成二维码的好库,我们只要把数据传给QRCode()就可以轻松创建一个二维码,当然也可以设置二维码的容错率、样式等

import pyotp
import traceback
from qrcode import QRCode, constants

def get_google_qrcode(token, username):
    # dirpath = "./img"
    data = pyotp.totp.TOTP(token).provisioning_uri(username, issuer_name="qrCode")
    qr = QRCode(error_correction=constants.ERROR_CORRECT_L, version=1, box_size=6, border=4)
    try:
        qr.add_data(data)
        qr.make(fit=True)
        img = qr.make_image()
        # filepath = "xxx.png"
        # img.save(filepath)  # 保存条形码图片
        # return True, filepath
        return img
    except Exception as e:
        traceback.print_exc()
        # return False, None
        return None
# View视图函数内
qrcode = get_google_qrcode(google_auth.token, user.username)
if not qrcode:
    res_data.update({"error": "生成谷歌验证码失败"})
    return JsonResponse(res_data)
buf = BytesIO()
qrcode.save(buf)
image_stream = buf.getvalue()
# django返回
response = HttpResponse(image_stream, content_type="image/png")
return response

上面的方法返回的 是一个二进制流文件,不好在前端展示,还可以转成base64编码

qrcode = get_google_qrcode(google_auth.token, user.username)
if not qrcode:
    res_data.update({"error": "生成谷歌验证码失败"})
    return JsonResponse(res_data)
out = BytesIO()
qrcode.save(out, 'PNG')
pic_base64 = base64.b64encode(out.getvalue()).decode('ascii')
print("pic_base64:", pic_base64)
....
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰冷的希望

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值