Django中使用qrcode生成二维码

  • 2019 年 10 月 7 日
  • 笔记

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/bbwangj/article/details/101286449

qrcode简介

二维码简称 QR Code(Quick Response Code),学名为快速响应矩阵码,是二维条码的一种,由日本的 Denso Wave 公司于1994 年发明。现随着智能手机的普及,已广泛应用于平常生活中,例如商品信息查询、社交好友互动、网络地址访问等等。qrcode模块是Github上的一个开源项目,提供了生成二维码的接口。qrcode默认使用PIL库用于生成图像。由于生成 qrcode 图片需要依赖 Python 的图像库,所以需要先安装 Python 图像库 PIL(Python Imaging Library)。

GITHUB地址:https://github.com/sylnsfar/qrcode 1、安装qrcode和pillow pip install qrcode pillow 2、安装完成后直接使用,示例如下: import qrcode img=qrcode.make("http://www.feiutech.com") with open("test.png","wb") as f: img.save(f) 在python下运行它即可生成一个二维码

3、在django中使用

views.py

from django.http import HttpResponse  import qrcode  from django.utils.six import BytesIO  def  makeqrcode(request,data):      url = HOST+data      img = qrcode.make(url)      #传入网址计算出二维码图片字节数据      buf = BytesIO()                                 #创建一个BytesIO临时保存生成图片数据      img.save(buf)                                   #将图片字节数据放到BytesIO临时保存      image_stream = buf.getvalue()                   #在BytesIO临时保存拿出数据      response = HttpResponse(image_stream, content_type="image/jpg")  #将二维码数据返回到页面      return response

url.py

urlpatterns = [      ......      url(r'qrcode/(.+)$', views.makeqrcode,name='qrcode')      ......  ]

模板中使用 <img src="{% url 'qrcode' request.path %}" width="120px" height="120px;">