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;">
