登录验证码是每个网站登录时的基本标配,网上也有很多相应的文章, 但是从生成验证码到 应用到自己的网站上的全步骤,并没有看到很多, 为了节约大家的时间,我把整体步骤写下来, 即拿即用哈
1. 生成随机验证码
1 #_*_coding:utf-8_*_ 2 3 from PIL import Image,ImageDraw,ImageFont,ImageFilter 4 5 import random 6 import math, string 7 8 9 #字体的位置,不同版本的系统会有不同 10 font_path = '/Library/Fonts/Arial.ttf' 11 #font_path = '/Library/Fonts/Hanzipen.ttc' 12 #生成几位数的验证码 13 number = 4 14 #生成验证码图片的高度和宽度 15 size = (100,30) 16 #背景颜色,默认为白色 17 bgcolor = (255,255,255) 18 #字体颜色,默认为蓝色 19 fontcolor = (0,0,255) 20 #干扰线颜色。默认为红色 21 linecolor = (255,0,0) 22 #是否要加入干扰线 23 draw_line = True 24 #加入干扰线条数的上下限 25 line_number = (1,5) 26 27 28 29 30 def gen_text(): 31 source = list(string.ascii_letters) 32 for index in range(0,10): 33 source.append(str(index)) 34 return ''.join(random.sample(source,number))#number是生成验证码的位数 35 36 37 #用来绘制干扰线 38 def gene_line(draw,width,height): 39 begin = (random.randint(0, width), random.randint(0, height)) 40 end = (random.randint(0, width), random.randint(0, height)) 41 draw.line([begin, end], fill = linecolor) 42 43 def gene_code(save_path,filename): 44 width,height = size #宽和高 45 image = Image.new('RGBA',(width,height),bgcolor) #创建图片 46 47 font = ImageFont.truetype(font_path,25) #验证码的字体和字体大小 48 #font = ImageFont.truetype(25) #验证码的字体和字体大小 49 draw = ImageDraw.Draw(image) #创建画笔 50 #text = "我是中国人" #生成字符串 51 text = gen_text() #生成字符串 52 print(text) 53 font_width, font_height = font.getsize(text) 54 draw.text(((width - font_width) / number, (height - font_height) / number),text, 55 font= font,fill=fontcolor) #填充字符串 56 57 if draw_line: 58 gene_line(draw, width, height) 59 gene_line(draw, width, height) 60 gene_line(draw, width, height) 61 gene_line(draw, width, height) 62 63 image = image.transform((width + 20, height +10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) # 创建扭曲 64 image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强 65 image.save('%s/%s.png' %(save_path,filename)) # 保存验证码图片 66 print("savepath:",save_path) 67 return text 68 69 if __name__ == "__main__": 70 gene_code('/tmp','test') #会把生成的图片存成/tmp/test.png
2. 如何应用到你的django项目中
整个验证码的流程如下
- 用户访问登录页面,你的后台程序在给用户返回登录页面时,同时生成了验证码图片
- 用户输入账户信息和验证码数字,提交表单
- 后台判断用户输入的验证码和你生成的图片信息是否一致,如果一致,就代表验证码是没有问题的
问题就卡在第3步,你在第1步生成验证码并返回给用户后,由于一会用户还需要把这个验证码提交过来,你在后台就需要拿用户输入的和你之前生成 的验证码进行对比是否相等,
所以你必须在生成验证码的同时,把验证码存下来,存到哪? 必然是缓存,这样直接在存的同时加个超时时间 , 就可以限定验证码有效期了。
那存入缓存时的key是设置成什么呢?为了保证验证码的安全,我采取了以下设计
3.代码实现
login视图
1 def acc_login(request): 2 err_msg = {} 3 today_str = datetime.date.today().strftime("%Y%m%d") 4 verify_code_img_path = "%s/%s" %(settings.VERIFICATION_CODE_IMGS_DIR, 5 today_str) 6 if not os.path.isdir(verify_code_img_path): 7 os.makedirs(verify_code_img_path,exist_ok=True) 8 print("session:",request.session.session_key) 9 #print("session:",request.META.items()) 10 random_filename = "".join(random.sample(string.ascii_lowercase,4)) 11 random_code = verify_code.gene_code(verify_code_img_path,random_filename) 12 cache.set(random_filename, random_code,30) 13 14 if request.method == "POST": 15 16 username = request.POST.get('username') 17 password = request.POST.get('password') 18 _verify_code = request.POST.get('verify_code') 19 _verify_code_key = request.POST.get('verify_code_key') 20 21 print("verify_code_key:",_verify_code_key) 22 print("verify_code:",_verify_code) 23 if cache.get(_verify_code_key) == _verify_code: 24 print("code verification pass!") 25 26 user = authenticate(username=username,password=password) 27 if user is not None: 28 login(request,user) 29 request.session.set_expiry(60*60) 30 return HttpResponseRedirect(request.GET.get("next") if request.GET.get("next") else "/") 31 32 else: 33 err_msg["error"] = 'Wrong username or password!' 34 35 else: 36 err_msg['error'] = "验证码错误!" 37 38 return render(request,'login.html',{"filename":random_filename, "today_str":today_str, "error":err_msg})
template文件
1 {% extends 'base.html' %} 2 3 {% block body %} 4 <div id="container" class="cls-container"> 5 6 <!-- BACKGROUND IMAGE --> 7 <!--===================================================--> 8 <div id="bg-overlay" class="bg-img img-balloon"></div> 9 10 11 <!-- HEADER --> 12 <!--===================================================--> 13 <div class="cls-header cls-header-lg"> 14 <div class="cls-brand"> 15 <a class="box-inline" href="index.html"> 16 <!-- <img alt="Nifty Admin" src="img/logo.png" class="brand-icon"> --> 17 <span class="brand-title">PerfectCRM <span class="text-thin">老男孩教育</span></span> 18 </a> 19 </div> 20 </div> 21 <!--===================================================--> 22 23 24 <!-- LOGIN FORM --> 25 <!--===================================================--> 26 <div class="cls-content"> 27 <div class="cls-content-sm panel"> 28 <div class="panel-body"> 29 <p class="pad-btm">Sign In to your account</p> 30 <form method="post">{% csrf_token %} 31 <div class="form-group"> 32 <div class="input-group"> 33 <div class="input-group-addon"><i class="fa fa-user"></i></div> 34 <input type="text" name="username" class="form-control" placeholder="Username"> 35 </div> 36 </div> 37 <div class="form-group"> 38 <div class="input-group"> 39 <div class="input-group-addon"><i class="fa fa-asterisk"></i></div> 40 <input type="password" name="password" class="form-control" placeholder="Password"> 41 </div> 42 </div> 43 <div class="form-group"> 44 <div class="input-group"> 45 <div class="input-group-addon"> 46 <img height="30px" src="/static/verify_code_imgs/{{ today_str }}/{{ filename }}.png"> 47 </div> 48 <input style="height: 50px" type="text" name="verify_code" class="form-control" placeholder="验证码"> 49 <input type="hidden" name="verify_code_key" value="{{ filename }}" > 50 </div> 51 </div> 52 <div class="row"> 53 <div class="col-xs-8 text-left checkbox"> 54 <label class="form-checkbox form-icon"> 55 <input type="checkbox"> Remember me 56 </label> 57 </div> 58 <div class="col-xs-4"> 59 <div class="form-group text-right"> 60 <button class="btn btn-success text-uppercase" type="submit">Sign In</button> 61 </div> 62 </div> 63 </div> 64 {% if error %} 65 <span style="color: red">{{ error.error }}</span> 66 {% endif %} 67 68 </form> 69 </div> 70 </div> 71 <div class="pad-ver"> 72 <a href="pages-password-reminder.html" class="btn-link mar-rgt">Forgot password ?</a> 73 <a href="pages-register.html" class="btn-link mar-lft">Create a new account</a> 74 </div> 75 </div> 76 <!--===================================================--> 77 78 79 80 </div> 81 <!--===================================================--> 82 <!-- END OF CONTAINER --> 83 {% endblock %}