第三百二十節,Django框架,生成二維碼
用Python來生成二維碼,需要qrcode模塊,qrcode模塊依賴Image 模塊,所以首先安裝這兩個模塊
生成二維碼保存圖片在本地
import qrcode img = qrcode.make('http://www.jxiou.com') # img <qrcode.image.pil.PilImage object at 0x1044ed9d0> with open('test.png', 'wb') as f: img.save(f)
Python中調用:
import qrcode from qrcode.image.pure import PymagingImage img = qrcode.make('Some data here', image_factory=PymagingImage)
Django 中使用
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="/static/css/tou.css"> </head> <body> <img src="/bugyanzhm/"/> </body> </html>
路由映射
from django.conf.urls import url from django.contrib import admin from app1 import views urlpatterns = [ url(r'admin/', admin.site.urls), #路由映射admin數據庫管理 url(r'articles/', views.special), url(r'yanzhm/', views.yanzhm) ]
邏輯處理
from django.shortcuts import render,redirect,HttpResponse import qrcode from django.utils.six import BytesIO #邏輯處理模塊 def special(request): return render(request, 'app1/index.html') def yanzhm(request): img = qrcode.make('http://www.jxiou.com/') #傳入網站計算出二維碼圖片字節數據 buf = BytesIO() #創建一個BytesIO臨時保存生成圖片數據 img.save(buf) #將圖片字節數據放到BytesIO臨時保存 image_stream = buf.getvalue() #在BytesIO臨時保存拿出數據 response = HttpResponse(image_stream, content_type="image/jpg") #將二維碼數據返回到頁面 return response

