2019-05-10 13:20:07 2815瀏覽
今天千鋒扣丁學堂Python培訓老師給大家分享一篇關于Django框架驗證碼用法實例分析,結合實例形式分析了PythonDjango框架驗證碼的功能、實現(xiàn)方法及相關操作技巧,下面我們一起來看一下吧。
繪制驗證碼圖片 background = (10,20,30) // RGB顏色 初始化畫布 image = Image.new(‘RGB',(100,50),background) 獲取畫布中畫筆對象 draw = ImageDraw.Draw(image) 繪制驗證碼,隨機四個 font = ImageFont.truetype(‘path',size) fontcolor = (20,40,60) draw.text((x,y),'R',font,fontcolor) 返回驗證碼內(nèi)容 # 刪除畫筆 del draw #保存圖片到BytesIO對象 Import io buf = io.BytesIO() image.save(buf,'png') #返回BytesIO中的內(nèi)容 return HttpResponse(buf.getvalue(),'image/png')
<form method="post" action="{% url 'sitesApp:login' %}"> {% csrf_token %} <div class="login"> <div class="input-group"> <span class="input-group-addon" id="basic-addon1">用戶名</span> <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1" name="uName"> </div> <div class="input-group"> <span class="input-group-addon" id="basic-addon1">密 碼</span> <input type="text" class="form-control" placeholder="Password" aria-describedby="basic-addon1" name="uPswd"> </div> <div class="input-group"> <span class="input-group-addon" id="basic-addon1">驗證碼</span> <input type="text" class="form-control" placeholder="Auth code" aria-describedby="basic-addon1" name="uCode"> </div> <div class="vcode"> <img src="/app/getvcode/" id="vcode"> </div> <input type="submit" class="loginBtn" value="登 錄"><br> </div> </form> <script type="text/javascript"> $(function () { $('#vcode').click(function () { $(this).attr('src',"/app/getvcode"+Math.random()) }) }) </script>
''' 生成并返回驗證碼 ''' def getvcode(request): # 隨機生成驗證碼 population = string.ascii_letters+string.digits letterlist = random.sample(population,4) vcode = ''.join(letterlist) # 保存該用戶的驗證碼 request.session['vcode']=vcode # 繪制驗證碼 # 需要畫布,長寬顏色 image = Image.new('RGB',(176,60),color=getRandomColor()) # 創(chuàng)建畫布的畫筆 draw = ImageDraw.Draw(image) # 繪制文字,字體所在位置 path = os.path.join(BASE_DIR,'static','fonts','ADOBEARABIC-BOLDITALIC.OTF') font = ImageFont.truetype(path,50) for i in range(len(vcode)): draw.text((20+40*i,0),vcode[i],fill=getRandomColor(),font=font) # 添加噪聲 for i in range(500): position = (random.randint(0,176),random.randint(0,50)) draw.point(position,fill=getRandomColor()) # 返回驗證碼字節(jié)數(shù)據(jù) # 創(chuàng)建字節(jié)容器 buffer = io.BytesIO() # 將畫布內(nèi)容丟入容器 image.save(buffer,'png') # 返回容器內(nèi)的字節(jié) return HttpResponse(buffer.getvalue(),'image/png') # 獲取隨機顏色 def getRandomColor(): red = random.randint(0,255) green = random.randint(0,255) blue = random.randint(0,255) return (red,green,blue)
【關注微信公眾號獲取更多學習資料】 【掃碼進入Python全棧開發(fā)免費公開課】