Django之验证码

  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 
  4 import random
  5 from PIL import Image, ImageDraw, ImageFont, ImageFilter
  6 
  7 _letter_cases = "abcdefghjkmnpqrstuvwxy"  # 小写字母,去除可能干扰的i,l,o,z
  8 _upper_cases = _letter_cases.upper()  # 大写字母
  9 _numbers = ''.join(map(str, range(3, 10)))  # 数字
 10 init_chars = ''.join((_letter_cases, _upper_cases, _numbers))
 11 
 12 
 13 def create_validate_code(size=(120, 30),
 14                          chars=init_chars,
 15                          img_type="GIF",
 16                          mode="RGB",
 17                          bg_color=(255, 255, 255),
 18                          fg_color=(0, 0, 255),
 19                          font_size=18,
 20                          font_type="Monaco.ttf",
 21                          length=4,
 22                          draw_lines=True,
 23                          n_line=(1, 2),
 24                          draw_points=True,
 25                          point_chance=2):
 26     """
 27     @todo: 生成验证码图片
 28     @param size: 图片的大小,格式(宽,高),默认为(120, 30)
 29     @param chars: 允许的字符集合,格式字符串
 30     @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
 31     @param mode: 图片模式,默认为RGB
 32     @param bg_color: 背景颜色,默认为白色
 33     @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
 34     @param font_size: 验证码字体大小
 35     @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
 36     @param length: 验证码字符个数
 37     @param draw_lines: 是否划干扰线
 38     @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
 39     @param draw_points: 是否画干扰点
 40     @param point_chance: 干扰点出现的概率,大小范围[0, 100]
 41     @return: [0]: PIL Image实例
 42     @return: [1]: 验证码图片中的字符串
 43     """
 44 
 45     width, height = size  # 宽高
 46     # 创建图形
 47     img = Image.new(mode, size, bg_color)
 48     draw = ImageDraw.Draw(img)  # 创建画笔
 49 
 50     def get_chars():
 51         """生成给定长度的字符串,返回列表格式"""
 52         return random.sample(chars, length)
 53 
 54     def create_lines():
 55         """绘制干扰线"""
 56         line_num = random.randint(*n_line)  # 干扰线条数
 57 
 58         for i in range(line_num):
 59             # 起始点
 60             begin = (random.randint(0, size[0]), random.randint(0, size[1]))
 61             # 结束点
 62             end = (random.randint(0, size[0]), random.randint(0, size[1]))
 63             draw.line([begin, end], fill=(0, 0, 0))
 64 
 65     def create_points():
 66         """绘制干扰点"""
 67         chance = min(100, max(0, int(point_chance)))  # 大小限制在[0, 100]
 68 
 69         for w in range(width):
 70             for h in range(height):
 71                 tmp = random.randint(0, 100)
 72                 if tmp > 100 - chance:
 73                     draw.point((w, h), fill=(0, 0, 0))
 74 
 75     def create_strs():
 76         """绘制验证码字符"""
 77         c_chars = get_chars()
 78         strs = ' %s ' % ' '.join(c_chars)  # 每个字符前后以空格隔开
 79 
 80         font = ImageFont.truetype(font_type, font_size)
 81         font_width, font_height = font.getsize(strs)
 82 
 83         draw.text(((width - font_width) / 3, (height - font_height) / 3),
 84                   strs, font=font, fill=fg_color)
 85 
 86         return ''.join(c_chars)
 87 
 88     if draw_lines:
 89         create_lines()
 90     if draw_points:
 91         create_points()
 92     strs = create_strs()
 93 
 94     # 图形扭曲参数
 95     params = [1 - float(random.randint(1, 2)) / 100,
 96               0,
 97               0,
 98               0,
 99               1 - float(random.randint(1, 10)) / 100,
100               float(random.randint(1, 2)) / 500,
101               0.001,
102               float(random.randint(1, 2)) / 500
103               ]
104     img = img.transform(size, Image.PERSPECTIVE, params)  # 创建扭曲
105 
106     img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 滤镜,边界加强(阈值更大)
107 
108     return img, strs

视图函数:

 1 from app03.views.check_code import create_validate_code
 2 from io import BytesIO
 3 
 4 
 5 def check_code(request):
 6     stream = BytesIO()
 7     img, code = create_validate_code()
 8     img.save(stream, 'PNG')
 9     request.session['CheckCode'] = code
10     return HttpResponse(stream.getvalue())
11 
12 def login(request):
13     """
14     登陆
15     :param request:
16     :return:
17     """
18     # if request.method == "POST":
19     #     if request.session['CheckCode'].upper() == request.POST.get('check_code').upper():
20     #         pass
21     #     else:
22     #         print('验证码错误')
23     if request.method == 'POST':
24         code = request.POST.get('check_code')
25         if code.upper() == request.session['CheckCode'].upper():
26             print('验证码正确')
27         else:
28             print('验证码错误')
29     return render(request, 'login.html')
 1 <div class="col-xs-7">
 2     <input type="text" class="form-control" placeholder="请输入验证码" name="check_code">
 3 </div>
 4 <div class="col-xs-5">
 5     <h1 style="color: pink">验证码</h1>
 6     <img src="/app03/check_code.html" onclick="changeCheckCode(this);">
 7 </div>
 8 
 9 <script>
10     function changeCheckCode(ths){
11         ths.src = ths.src +  '?';
12     }
13 </script>

字体文件

滑动验证码:

1、打开插件,找到自己需要的验证码

2、筛选有用的路径

3、把对应的视图函数也拿过来,注意还需要一个geetest.py的文件

1 #滑动验证码
2      url(r'^pc-geetest/register', pcgetcaptcha, name='pcgetcaptcha'),
3      url(r'^pc-geetest/ajax_validate', pcajax_validate, name='pcajax_validate'),
urls
 1 # ================
 2 from app01.geetest import GeetestLib
 3 pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
 4 pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"
 5 mobile_geetest_id = "7c25da6fe21944cfe507d2f9876775a9"
 6 mobile_geetest_key = "f5883f4ee3bd4fa8caec67941de1b903"
 7 # 滑动验证码
 8 def pcgetcaptcha(request):
 9     user_id = 'test'
10     gt = GeetestLib(pc_geetest_id, pc_geetest_key)
11     status = gt.pre_process(user_id)
12     request.session[gt.GT_STATUS_SESSION_KEY] = status
13     request.session["user_id"] = user_id
14     response_str = gt.get_response_str()
15     return HttpResponse(response_str)
16 # 滑动验证码
17 def pcajax_validate(request):
18 
19     if request.method == "POST":
20         # 验证的验证码
21         ret = {"flag": False, "error_msg": None}
22         gt = GeetestLib(pc_geetest_id, pc_geetest_key)
23         challenge = request.POST.get(gt.FN_CHALLENGE, '')
24         validate = request.POST.get(gt.FN_VALIDATE, '')
25         seccode = request.POST.get(gt.FN_SECCODE, '')
26         status = request.session[gt.GT_STATUS_SESSION_KEY]
27         user_id = request.session["user_id"]
28         print("status",status)
29         if status:
30             result = gt.success_validate(challenge, validate, seccode, user_id)
31         else:
32             result = gt.failback_validate(challenge, validate, seccode)
33         if result:  #如果验证验证码正确,就验证用户名是否正确
34             username = request.POST.get("username")
35             password = request.POST.get("password")
36 
37            # 验证用户名和密码
38             user = auth.authenticate(username=username, password=password)
39             if user:
40                 # 如果验证成功就让登录
41                 ret["flag"] = True
42                 auth.login(request, user)
43             else:
44                 ret["error_msg"] = "用户名和密码错误"
45         else:
46             ret["error_msg"] = "验证码错误"
47         return HttpResponse(json.dumps(ret))
48     else:
49         return render(request, "login.html")
views
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6     <meta name="viewport" content="width=device-width">
  7     <title>Title</title>
  8     <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
  9     <link rel="stylesheet" href="/static/css/login.css">
 10     <script src="/static/jquery-3.2.1.min.js"></script>
 11    滑动验证码的时候导入
 12     <script src="http://static.geetest.com/static/tools/gt.js"></script>
 13     <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
 14     <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
 15 
 16 </head>
 17 <body>
 18 <div class="container">
 19     <div class="row">
 20         <div class="col-md-1=10">
 21             <form class="form-horizontal" id="form_data" action="/login/" method="post">
 22                 {% csrf_token %}
 23                 <div class="form-group">
 24                     <label for="username" class="col-sm-2 control-label">用户名</label>
 25                     <div class="col-sm-5">
 26                         <input type="text" class="form-control" id="username" placeholder="username" name="username">
 27                     </div>
 28                 </div>
 29                 <div class="form-group">
 30                     <label for="password" class="col-sm-2 control-label">密码</label>
 31                     <div class="col-sm-5">
 32                         <input type="password" class="form-control" id="password" placeholder="password" name="password">
 33                     </div>
 34                 </div>
 35                 <div class="form-group">
 36                     <div class="row">
 37                         <div class="col-md-6 col-md-offset-1">
 38 {#                            文字部分#}
 39                             <label for="vialdCode" class="col-sm-2 control-label">验证码</label>
 40                              <div class="col-sm-5">
 41                                 <input type="text" class="form-control vialdCode_text" id="vialdCode" placeholder="验证码" name="vialdCode">
 42                             </div>
 43 {#                            图片部分#}
 44                              <div class="col-md-5">
 45                             <img class="vialdCode_img" src="/get_vaildCode_img/" alt="" width="200px" height="100px">
 46 {#                                 <a href=""></a>     #}
 47                         </div>
 48                         </div>
 49 
 50                     </div>
 51                 </div>
 52                 <div class="form-group">
 53                     <div class="col-sm-offset-2 col-sm-10">
 54                         <div class="checkbox">
 55                             <label>
 56                                 <input type="checkbox"> 下次自动登录
 57                             </label>
 58                         </div>
 59                     </div>
 60                 </div>
 61                 <div class="form-group">
 62                     <div class="col-sm-offset-2 col-sm-10">
 63                         <p>
 64                             <button type="button" class="btn btn-success login" id="submit">登录</button>
 65                             <span class="error has-error"></span></p>
 66                         <p>
 67                             <button type="button" class="btn btn-primary register">注册</button>
 68                         </p>
 69                     </div>
 70                     <div id="popup-captcha"></div>
 71                 </div>
 72             </form>
 73         </div>
 74     </div>
 75 </div>
 76 {#滑动验证码#}
 77 <script>
 78     var handlerPopup = function (captchaObj) {
 79         $("#submit").click(function () {
 80             captchaObj.show();
 81         });
 82         //定时函数
 83          $(".login").click(function () {
 84              function foo() {
 85                  $(".error").html("")
 86              }
 87 
 88              // 成功的回调
 89              captchaObj.onSuccess(function () {
 90                  var validate = captchaObj.getValidate();
 91                  $.ajax({
 92                      url: "/pc-geetest/ajax_validate", // 进行二次验证
 93                      type: "post",
 94                      dataType: "json",
 95                      headers: {"X-CSRFToken": $.cookie('csrftoken')},
 96                      data: {
 97                          username: $('#username').val(),
 98                          password: $('#password').val(),
 99                          geetest_challenge: validate.geetest_challenge,
100                          geetest_validate: validate.geetest_validate,
101                          geetest_seccode: validate.geetest_seccode
102                      },
103                      success: function (data) {
104                          console.log(data);
105                          if (data["flag"]) {
106 {#                             alert(location.search);#}
107 {#                             alert(location.search.slice(6));#}
108 {#                             方式一#}
109 {#                             if (location.search.slice(6)) {#}
110                                  {#                            如果用户没有登录点赞的时候,当用户后来又登录了,就直接让跳转到当前点赞的那个路径#}
111 {#                                 location.href = location.search.slice(6)#}
112 {#                             }#}
113 {#                             else {#}
114 {#                                 window.location.href = '/index/'#}
115 {#                             }#}
116 {#                             方式二:#}
117                              alert($.cookie("next_path"));
118                              if ($.cookie("next_path")){
119                                  location.href = $.cookie("next_path")
120                              }
121                              else{
122                                  location.href = "/index/"
123                              }
124                          }
125                          else {
126                              $(".error").html(data["error_msg"]);
127                              setTimeout(foo, 3000)
128                          }
129                      }
130                  });
131              });
132 
133          });
134              // 将验证码加到id为captcha的元素里
135              captchaObj.appendTo("#popup-captcha");
136              // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
137          };
138     // 验证开始需要向网站主后台获取id,challenge,success(是否启用failback)
139     $.ajax({
140         url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
141         type: "get",
142         dataType: "json",
143         success: function (data) {
144             // 使用initGeetest接口
145             // 参数1:配置参数
146             // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
147             initGeetest({
148                 gt: data.gt,
149                 challenge: data.challenge,
150                 product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
151                 offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
152                 // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
153             }, handlerPopup);
154         }
155     });
156 </script>
login.html

猜你喜欢

转载自www.cnblogs.com/yum777/p/8926615.html