Django中的验证码
2019-02-01 本文已影响0人
临渊如峙
1、View
def verification_code(request):
bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
width = 100
height = 25
# 创建画面对象
# im = Image.new('RGB', (width, height), bgcolor)
im = Image.new('RGB', (width, height), (255, 255, 255))
# 创建画笔对象
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))]
# 构造字体对象
font = ImageFont.truetype('simsun.ttc', 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
# 创建内存读写的对象
buf = BytesIO()
# 将图片保存在内存中,文件类型为png
im.save(buf, 'png')
# 放入session中
request.session['verificationcode'] = rand_str
request.session.set_expiry(0)
return HttpResponse(buf.getvalue(), 'image/png')
2、Template
<td>验证码</td>
<td><input type="text" name="verificationcode"/></td>
<td><img src="/user/verification_code" alt="验证码" id="verificationcode"/></td>
<script>
window.onload = function(){
src = "/user/verification_code?n="
code = document.getElementById("verificationcode")
//为验证码添加click事件
code.onclick = function(){
code.src = src + new Date().getTime()
}
}
</script>