驗證碼
在使用者注冊、登入頁面,為了防止暴力請求,可以加入驗證碼功能,如果驗證碼錯誤,則不需要繼續處理,可以減輕業務伺服器、資料庫伺服器的壓力。
手動實作驗證碼
接下來的代碼不要求手動寫出來,因為這種代碼在網上可以搜到很多。
1)安裝包Pillow3.4.1。
pip install Pillow==3.4.1
以下代碼中用到了Image、ImageDraw、ImageFont對象及方法。
2)在booktest/views.py檔案中,建立視圖verify_code。
提示1:随機生成字元串後存入session中,用于後續判斷。
提示2:視圖傳回mime-type為image/png。
from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO
...
def verify_code(request):
#引入随機函數子產品
import random
#定義變量,用于畫面的背景色、寬、高
bgcolor = (random.randrange(20, 100), random.randrange(
20, 100), 255)
width = 100
height = 25
#建立畫面對象
im = Image.new('RGB', (width, height), bgcolor)
#建立畫筆對象
draw = ImageDraw.Draw(im)
#調用畫筆的point()函數繪制噪點
for i in range(0, 100):
xy = (random.randrange(0, width), random.randrange(0, height))
fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
draw.point(xy, fill=fill)
#定義驗證碼的備選值
str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
#随機選取4個值作為驗證碼
rand_str = ''
for i in range(0, 4):
rand_str += str1[random.randrange(0, len(str1))]
#構造字型對象,ubuntu的字型路徑為“/usr/share/fonts/truetype/freefont”
font = ImageFont.truetype('FreeMono.ttf', 23)
#構造字型顔色
fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
#繪制4個字
draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
#釋放畫筆
del draw
#存入session,用于做進一步驗證
request.session['verifycode'] = rand_str
#記憶體檔案操作
buf = BytesIO()
#将圖檔儲存在記憶體中,檔案類型為png
im.save(buf, 'png')
#将記憶體中的圖檔資料傳回給用戶端,MIME類型為圖檔png
return HttpResponse(buf.getvalue(), 'image/png')
3)打開booktest/urls.py檔案,配置url。
url(r'^verify_code/$', views.verify_code),
4)運作伺服器,在浏覽器中輸入如下網址。
http://127.0.0.1:8000/verify_code/
5)浏覽效果如下圖:
可以多重新整理幾次看值會不會變。
調用驗證碼
1)在booktest/views.py檔案中,建立視圖verify_show。
def verify_show(request):
return render(request,'booktest/verify_show.html')
2)打開booktest/urls.py檔案,配置url。
url(r'^verify_show/$', views.verify_show),
3)在templates/booktest/目錄下建立verify_show.html。
<html>
<head>
<title>驗證碼</title>
</head>
<body>
<form method="post" action="/verify_yz/">
{%csrf_token%}
<input type="text" name="yzm">
<img id="yzm" src="/verify_code/"/>
<span id="change">看不清,換一個</span>
<br>
<input type="submit" value="送出">
</form>
</body>
</html>
4)運作伺服器,在浏覽器中輸入如下網址。
http://127.0.0.1:8000/verify_show/
5)浏覽效果如下圖:
驗證
1)在booktest/views.py檔案中,建立視圖verify_yz。
def verify_yz(request):
yzm=request.POST.get('yzm')
verifycode=request.session['verifycode']
response=HttpResponse('no')
if yzm==verifycode:
response=HttpResponse('ok')
return response
2)打開booktest/urls.py檔案,配置url。
url(r'^verify_yz/$', views.verify_yz),
3)回到浏覽器後重新整理,在文本框中填寫驗證碼,點選送出按鈕。
4)浏覽效果如下圖: