作用:在用户注册登录界面的时候应用,为了防止暴力请求,减轻服务器压力
也是防止csrf的一种方式
def verifycode(request):
from PIL import Image,ImageDraw,ImageFont
#from PIL.Image import point
import random
bgcolor=(random.randrange(20,100),random.randrange(20,100),random.randrange(20,100))
width=100
height=50
im=Image.new(‘RGB‘,(width,height),bgcolor)
draw=ImageDraw.Draw(im)
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)
str=‘1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKL‘
rand_str=‘‘
for i in range(0,4):
rand_str+=str[random.randrange(0,len(str))]
font=ImageFont.truetype(r‘?C:\Windows\Fonts\arial.ttf‘,40)
fontcolor1=(255,random.randrange(0,255),random.randrange(0,255))
fontcolor2 = (255, random.randrange(0, 255), random.randrange(0, 255))
fontcolor3 = (255, random.randrange(0, 255), random.randrange(0, 255))
fontcolor4 = (255, random.randrange(0, 255), random.randrange(0, 255))
draw.text((5,2),rand_str[0],font=font,fill=fontcolor1)
draw.text((25, 2), rand_str[1], font=font, fill=fontcolor2)
draw.text((50, 2), rand_str[2], font=font, fill=fontcolor3)
draw.text((75, 2), rand_str[3], font=font, fill=fontcolor4)
del draw
request.session[‘verify‘]=rand_str
import io
buf=io.BytesIO()
im.save(buf,‘png‘)
return HttpResponse(buf.getvalue(),‘image/png‘)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/verifycodecheck/" method="post">
{% csrf_token %}
<input type="text" name="verifycode">
<img src="/verifycode/">
<input type="submit" value="登录">
<span>{{ flag }}</span>
</form>
</body>
</html>
def verifycodefile(request):
return render(request,‘app1/verifycodefile.html‘)
def verifycodecheck(request):
s=request.session.get("flag",True)
if s==False:
str="登录失败"
request.session.clear()
return render(request,‘app1/verifycodefile.html‘,{"flag":str})
code1= request.POST.get("verifycode").upper()
code2= request.session["verify"].upper()
if code1==code2:
return render(request,‘app1/success.html‘)
else:
request.session["flag"]=False
return redirect(‘/verifycodefile‘)
原文:https://www.cnblogs.com/rmxob/p/12632314.html