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)
....