使用Python的pillow模塊 random 模塊隨機生成驗證碼圖片,並應用到Django項目中前端
$ pip3 install pillow
\vericode.py from PIL import Image,ImageDraw,ImageFont,ImageFilter import random #隨機碼 默認長度=1 def random_code(lenght=1): code = '' for char in range(lenght): code += chr(random.randint(65,90)) return code #隨機顏色 默認顏色範圍【1,255】 def random_color(s=1,e=255): return (random.randint(s,e),random.randint(s,e),random.randint(s,e)) #生成驗證碼圖片 #length 驗證碼長度 #width 圖片寬度 #height 圖片高度 #返回驗證碼和圖片 def veri_code(lenght=4,width=160,height=40): #建立Image對象 image = Image.new('RGB',(width,height),(255,255,255)) #建立Font對象 font = ImageFont.truetype('Arial.ttf',32) #建立Draw對象 draw = ImageDraw.Draw(image) #隨機顏色填充每一個像素 for x in range(width): for y in range(height): draw.point((x,y),fill=random_color(64,255)) #驗證碼 code = random_code(lenght) #隨機顏色驗證碼寫到圖片上 for t in range(lenght): draw.text((40*t+5,5),code[t],font=font,fill=random_color(32,127)) #模糊濾鏡 image = image.filter(ImageFilter.BLUR) return code,image
編寫Django應用下的視圖函數django
\views.py from . import vericode.py from io import BytesIO from django.http import HttpResponse def verify_code(request): f = BytesIO() code,image = vericode.veri_code() image.save(f,'jpeg') request.session['vericode'] = code return HttpResponse(f.getvalue()) def submit_xxx(request): if request.method == "POST": vericode = request.session.get("vericode").upper() submitcode = request.POST.get("vericode").upper() if submitcode == vericode: return HttpResponse('ok') return HttpResponse('error')
這裏使用了Django的session,須要在Django settings.py的INSTALLED_APPS中添加'django.contrib.sessions'(默認添加)
verify_code視圖函數將驗證碼添加到session中和驗證碼圖片一塊兒發送給瀏覽器,當提交表單到submit_xxx()時,先從session中獲取驗證碼,再對比從表單中的輸入的驗證碼。
這裏只是簡單說明,url配置和前端代碼未給出。瀏覽器