烹茶细论

Django登陆验证码

内部的运维平台,安全测试之后需要添加验证码功能防止爆破。然后开始网上找教程,照着抄,备忘

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from PIL import Image, ImageDraw, ImageFont
import random, hashlib, datetime, cStringIO
def get_check_code_image(request,image='static/resources/images/code.png'):
try:
im = Image.open(image)
draw = ImageDraw.Draw(im)
mp = hashlib.md5()
# mp = md5.new()
mp_src = mp.update(str(datetime.datetime.now()))
mp_src = mp.hexdigest()
rand_str = mp_src[0:4]
draw.text((10,10), rand_str[0], font=ImageFont.truetype("static/resources/font/wqy.ttc", random.randrange(25,50)))
draw.text((48,10), rand_str[1], font=ImageFont.truetype("static/resources/font/wqy.ttc", random.randrange(25,50)))
draw.text((85,10), rand_str[2], font=ImageFont.truetype("static/resources/font/wqy.ttc", random.randrange(25,50)))
draw.text((120,10), rand_str[3], font=ImageFont.truetype("static/resources/font/wqy.ttc", random.randrange(25,50)))
del draw
request.session['checkcode'] = rand_str
buf = cStringIO.StringIO()
im.save(buf, 'png')
except Exception,e:
logging.error('get_check_code_image:'+str(e))
return HttpResponse(buf.getvalue(),'/login/png')

HTML

1
<img onclick=&quot;this.setAttribute('src','/login/image/?nocache='+Math.random());&quot; src=&quot;/login/image&quot; alt=&quot;CheckCode&quot; class=&quot;code-img&quot;/>;

效果
用户当天输错三次密码,则需要验证码

code