zoukankan      html  css  js  c++  java
  • flask实现验证码并验证

    效果图:

    点击图片、刷新页面、输入错误点击登录时都刷新验证码

     

    实现步骤:

    第一步:先定义获取验证码的接口

    verificationCode.py

    1 #验证码
    2 @api.route('/imgCode')
    3 def imgCode():
    4     return imageCode().getImgCode()

    此处的@api是在app下注册的蓝图,专门用来做后台接口,所以注册了api蓝图

     

    第二步:实现接口逻辑

     

    1)首先实现验证码肯定要随机生成,所以我们需要用到random库,本次需要随机生成字母和数字,

    所以我们还需要用到string。string的ascii_letters是生成所有字母 digits是生成所有数字0-9。具体代码如下

    1 def geneText():
    2     '''生成4位验证码'''
    3     return ''.join(random.sample(string.ascii_letters + string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有数字0-9

      2)为了美观,我们需要给每个随机字符设置不同的颜色。我们这里用一个随机数来给字符设置颜色

    1 def rndColor():
    2     '''随机颜色'''
    3     return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

      3)此时我们已经可以生产图片验证码了,利用上面的随机数字和随机颜色生成一个验证码图片。

      这里我们需要用到PIL库,此时注意,python3安装这个库的时候不是pip install PIL 而是pip install pillow。

     1 def getVerifyCode():
     2     '''生成验证码图形'''
     3     code = geneText()
     4     # 图片大小120×50
     5     width, height = 120, 50
     6     # 新图片对象
     7     im = Image.new('RGB', (width, height), 'white')
     8     # 字体
     9     font = ImageFont.truetype('app/static/arial.ttf', 40)
    10     # draw对象
    11     draw = ImageDraw.Draw(im)
    12     # 绘制字符串
    13     for item in range(4):
    14         draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
    15                   text=code[item], fill=rndColor(), font=font)
    16     return im, code

      4)此时,验证码图片已经生成。然后需要做的就是把图片发送到前端去展示。

     1 def getImgCode():
     2     image, code = getVerifyCode()
     3     # 图片以二进制形式写入
     4     buf = BytesIO()
     5     image.save(buf, 'jpeg')
     6     buf_str = buf.getvalue()
     7     # 把buf_str作为response返回前端,并设置首部字段
     8     response = make_response(buf_str)
     9     response.headers['Content-Type'] = 'image/gif'
    10     # 将验证码字符串储存在session中
    11     session['imageCode'] = code
    12     return response

      这里我们采用讲图片转换成二进制的形式,讲图片传送到前端,并且在这个返回值的头部,需要标明这是一个图片。

      将验证码字符串储存在session中,是为了一会在登录的时候,进行验证码验证。

      5)OK,此时我们的接口逻辑已经基本完成。然后我们还可以给图片增加以下干扰元素,比如增加一点横线。

    1 def drawLines(draw, num, width, height):
    2     '''划线'''
    3     for num in range(num):
    4         x1 = random.randint(0, width / 2)
    5         y1 = random.randint(0, height / 2)
    6         x2 = random.randint(0, width)
    7         y2 = random.randint(height / 2, height)
    8         draw.line(((x1, y1), (x2, y2)), fill='black', width=1)

      然后getVerifyCode函数需要新增一步

     1 def getVerifyCode():
     2     '''生成验证码图形'''
     3     code = geneText()
     4     # 图片大小120×50
     5     width, height = 120, 50
     6     # 新图片对象
     7     im = Image.new('RGB', (width, height), 'white')
     8     # 字体
     9     font = ImageFont.truetype('app/static/arial.ttf', 40)
    10     # draw对象
    11     draw = ImageDraw.Draw(im)
    12     # 绘制字符串
    13     for item in range(4):
    14         draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
    15                   text=code[item], fill=rndColor(), font=font)
    16     # 划线
    17     drawLines(draw, 2, width, height)
    18     return im, code

      最终接口逻辑完成。整体接口代码如下

     1 from .. import *
     2 from io import BytesIO
     3 import random
     4 import string
     5 from PIL import Image, ImageFont, ImageDraw, ImageFilter
     6 
     7 #验证码
     8 @api.route('/imgCode')
     9 def imgCode():
    10     return imageCode().getImgCode()
    11 
    12 
    13 class imageCode():
    14     '''
    15     验证码处理
    16     '''
    17     def rndColor(self):
    18         '''随机颜色'''
    19         return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
    20 
    21     def geneText(self):
    22         '''生成4位验证码'''
    23         return ''.join(random.sample(string.ascii_letters + string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有数字0-9
    24 
    25     def drawLines(self, draw, num, width, height):
    26         '''划线'''
    27         for num in range(num):
    28             x1 = random.randint(0, width / 2)
    29             y1 = random.randint(0, height / 2)
    30             x2 = random.randint(0, width)
    31             y2 = random.randint(height / 2, height)
    32             draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
    33 
    34     def getVerifyCode(self):
    35         '''生成验证码图形'''
    36         code = self.geneText()
    37         # 图片大小120×50
    38         width, height = 120, 50
    39         # 新图片对象
    40         im = Image.new('RGB', (width, height), 'white')
    41         # 字体
    42         font = ImageFont.truetype('app/static/arial.ttf', 40)
    43         # draw对象
    44         draw = ImageDraw.Draw(im)
    45         # 绘制字符串
    46         for item in range(4):
    47             draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
    48                       text=code[item], fill=self.rndColor(), font=font)
    49         # 划线
    50         self.drawLines(draw, 2, width, height)
    51         return im, code
    52 
    53     def getImgCode(self):
    54         image, code = self.getVerifyCode()
    55         # 图片以二进制形式写入
    56         buf = BytesIO()
    57         image.save(buf, 'jpeg')
    58         buf_str = buf.getvalue()
    59         # 把buf_str作为response返回前端,并设置首部字段
    60         response = make_response(buf_str)
    61         response.headers['Content-Type'] = 'image/gif'
    62         # 将验证码字符串储存在session中
    63         session['imageCode'] = code
    64         return response

     

    第三步:前端展示。

    这里前端我使用的是layui框架。其他框架类似。

    1 <div class="layui-form-item">
    2     <label class="layui-icon layui-icon-vercode" for="captcha"></label>
    3     <input type="text" name="captcha" lay-verify="required|captcha" placeholder="图形验证码" autocomplete="off"
    4            class="layui-input verification captcha" value="">
    5     <div class="captcha-img">
    6         <img id="verify_code" class="verify_code" src="/api/imgCode" onclick="this.src='/api/imgCode?'+ Math.random()">
    7     </div>
    8 </div>

    js:主要是针对验证失败以后,刷新图片验证码

     1             // 进行登录操作
     2             form.on('submit(login)', function (data) {
     3                 console.log(data.elem);
     4                 var form_data = data.field;
     5                 //加密成md5
     6                 form_data.password=$.md5(form_data.password);
     7                 $.ajax({
     8                     url: "{{ url_for('api.api_login') }}",
     9                     data: form_data,
    10                     dataType: 'json',
    11                     type: 'post',
    12                     success: function (data) {
    13                         if (data['code'] == 0) {
    14                             location.href = "{{ url_for('home.homes') }}";
    15                         } else {
    16                             //登录失败则刷新图片验证码
    17                             var tagImg = document.getElementById('verify_code');
    18                             tagImg.src='/api/imgCode?'+ Math.random();
    19                             console.log(data['msg']);
    20                             layer.msg(data['msg']);
    21                         }
    22                     }
    23                 });
    24                 return false;
    25             });

    第四步:验证码验证

    验证码验证需要在点击登录按钮以后,在对验证码进行效验

    1)首先我们获取到前端传过来的验证码。.lower()是为了忽略大小写

    这里的具体写法为什么这样写可以获取到前端传过来的参数,可以自行了解flask框架

    1 if request.method == 'POST':
    2     username = request.form.get('username')
    3     password = request.form.get('password')
    4     captcha = request.form.get('captcha').lower()

      2)对验证码进行验证.因为我们在生成验证码的时候,就已经把验证码保存到session中,这里直接取当时生成的验证码,然后跟前端传过来的值对比即可。

    1 if captcha==session['imageCode'].lower():
    2     pass
    3 else4     return jsonify({'code':-1,'msg':'图片验证码错误'})

    到此,已完成了获取验证码、显示验证码、验证验证码的所有流程。验证验证码中没有把整体代码写出来。可以根据自己情况自己写。

     

    注:转载请注明出处。谢谢合作~

  • 相关阅读:
    20145337《网络对抗技术》逆向及BOF基础
    20145337 《信息安全系统设计基础》课程总结
    微信小程序——3、逻辑js文件
    微信小程序——2、配置json文件
    微信小程序——1、文件的认识
    20145336 张子扬 《网络对抗技术》 web安全基础实践
    20145336 张子扬 《网络对抗技术》web基础
    20145336张子扬 《网络对抗技术》 网络欺诈技术防范
    20145336《网络对抗技术》Exp6 信息搜集技术
    20145336张子扬《网络对抗》MSF基础应用
  • 原文地址:https://www.cnblogs.com/huxiansheng/p/11987259.html
Copyright © 2011-2022 走看看