flask实现验证码并验证功能


Posted in Python onDecember 05, 2019

什么是Flask?

Flask是一个用Python编写的Web应用程序框架,Flask是python的web框架,最大的特征是轻便,让开发者自由灵活的兼容要开发的feature。 它由 Armin Ronacher 开发,他领导一个名为Pocco的国际Python爱好者团队。 Flask基于Werkzeug WSGI工具包和Jinja2模板引擎。两者都是Pocco项目。

效果图:

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

flask实现验证码并验证功能

实现步骤:

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

verificationCode.py

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

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

flask实现验证码并验证功能

第二步:实现接口逻辑

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

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

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

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

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

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

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

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

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

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

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

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

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

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

然后getVerifyCode函数需要新增一步

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

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

from .. import *
from io import BytesIO
import random
import string
from PIL import Image, ImageFont, ImageDraw, ImageFilter
#验证码
@api.route('/imgCode')
def imgCode():
  return imageCode().getImgCode()
class imageCode():
  '''
  验证码处理
  '''
  def rndColor(self):
    '''随机颜色'''
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
  def geneText(self):
    '''生成4位验证码'''
    return ''.join(random.sample(string.ascii_letters + string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有数字0-9
  def drawLines(self, draw, num, width, height):
    '''划线'''
    for num in range(num):
      x1 = random.randint(0, width / 2)
      y1 = random.randint(0, height / 2)
      x2 = random.randint(0, width)
      y2 = random.randint(height / 2, height)
      draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
  def getVerifyCode(self):
    '''生成验证码图形'''
    code = self.geneText()
    # 图片大小120×50
    width, height = 120, 50
    # 新图片对象
    im = Image.new('RGB', (width, height), 'white')
    # 字体
    font = ImageFont.truetype('app/static/arial.ttf', 40)
    # draw对象
    draw = ImageDraw.Draw(im)
    # 绘制字符串
    for item in range(4):
      draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
           text=code[item], fill=self.rndColor(), font=font)
    # 划线
    self.drawLines(draw, 2, width, height)
    return im, code
  def getImgCode(self):
    image, code = self.getVerifyCode()
    # 图片以二进制形式写入
    buf = BytesIO()
    image.save(buf, 'jpeg')
    buf_str = buf.getvalue()
    # 把buf_str作为response返回前端,并设置首部字段
    response = make_response(buf_str)
    response.headers['Content-Type'] = 'image/gif'
    # 将验证码字符串储存在session中
    session['imageCode'] = code
    return response

第三步:前端展示。

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

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

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

// 进行登录操作
      form.on('submit(login)', function (data) {
        console.log(data.elem);
        var form_data = data.field;
        //加密成md5
        form_data.password=$.md5(form_data.password);
        $.ajax({
          url: "{{ url_for('api.api_login') }}",
          data: form_data,
          dataType: 'json',
          type: 'post',
          success: function (data) {
            if (data['code'] == 0) {
              location.href = "{{ url_for('home.homes') }}";
            } else {
              //登录失败则刷新图片验证码
              var tagImg = document.getElementById('verify_code');
              tagImg.src='/api/imgCode?'+ Math.random();
              console.log(data['msg']);
              layer.msg(data['msg']);
            }
          }
        });
        return false;
      });

第四步:验证码验证

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

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

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

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

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

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

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

总结

以上所述是小编给大家介绍的flask实现验证码并验证功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
Python中文件I/O高效操作处理的技巧分享
Feb 04 Python
Python实现破解12306图片验证码的方法分析
Dec 29 Python
Python enumerate索引迭代代码解析
Jan 19 Python
基于pip install django失败时的解决方法
Jun 12 Python
Python中如何使用if语句处理列表实例代码
Feb 24 Python
python 模拟创建seafile 目录操作示例
Sep 26 Python
Python中生成一个指定长度的随机字符串实现示例
Nov 06 Python
解决Python3.8用pip安装turtle-0.0.2出现错误问题
Feb 11 Python
python实现FTP循环上传文件
Mar 20 Python
Python实现仿射密码的思路详解
Apr 23 Python
基于CentOS搭建Python Django环境过程解析
Aug 24 Python
python正则表达式re.search()的基本使用教程
May 21 Python
使用python写一个自动浏览文章的脚本实例
Dec 05 #Python
Python字节单位转换实例
Dec 05 #Python
使用Python paramiko模块利用多线程实现ssh并发执行操作
Dec 05 #Python
Python使用指定字符长度切分数据示例
Dec 05 #Python
python从zip中删除指定后缀文件(推荐)
Dec 05 #Python
python3 求约数的实例
Dec 05 #Python
python生成特定分布数的实例
Dec 05 #Python
You might like
深入理解PHP原理之错误抑制与内嵌HTML分析
2011/05/02 PHP
ecshop 批量上传(加入自定义属性)
2012/03/20 PHP
编写php应用程序实现摘要式身份验证的方法详解
2013/06/08 PHP
php取整函数ceil,floo,round的用法及介绍
2013/08/31 PHP
php常用图片处理类
2016/03/16 PHP
详解PHP的Yii框架的运行机制及其路由功能
2016/03/17 PHP
PHP7中I/O模型内核剖析详解
2019/04/14 PHP
php创建多级目录与级联删除文件的方法示例
2019/09/12 PHP
php更新cookie内容的详细方法
2019/09/30 PHP
JavaScript 对话框和状态栏使用说明
2009/10/25 Javascript
JavaScript OOP类与继承
2009/11/15 Javascript
基于jquery.Jcrop的头像编辑器
2010/03/01 Javascript
纯css+js写的一个简单的tab标签页带样式
2014/01/28 Javascript
JavaScript和CSS交互的方法汇总
2014/12/02 Javascript
移动设备手势事件库Touch.js使用详解
2017/08/18 Javascript
基于require.js的使用(实例讲解)
2017/09/07 Javascript
AngularJS 前台分页实现的示例代码
2018/06/07 Javascript
深入理解Vue router的部分高级用法
2018/08/15 Javascript
JavaScript查看代码运行效率console.time()与console.timeEnd()用法
2019/01/18 Javascript
基于vue框架手写一个notify插件实现通知功能的方法
2019/03/31 Javascript
Vue 图片压缩并上传至服务器功能
2020/01/15 Javascript
Python中的赋值、浅拷贝、深拷贝介绍
2015/03/09 Python
使用Python来开发Markdown脚本扩展的实例分享
2016/03/04 Python
Python中eval带来的潜在风险代码分析
2017/12/11 Python
详解Python 装饰器执行顺序迷思
2018/08/08 Python
Python global全局变量函数详解
2018/09/18 Python
在Pycharm terminal中字体大小设置的方法
2019/01/16 Python
python使用mitmproxy抓取浏览器请求的方法
2019/07/02 Python
python爬虫 2019中国好声音评论爬取过程解析
2019/08/26 Python
Django实现将views.py中的数据传递到前端html页面,并展示
2020/03/16 Python
jupyter notebook 的工作空间设置操作
2020/04/20 Python
使用before和:after伪类制作css3圆形按钮
2014/04/08 HTML / CSS
美国折扣香水网站:The Perfume Spot
2020/12/12 全球购物
What is the purpose of Void class? Void类的作用是什么?
2016/10/31 面试题
迎新晚会策划方案
2014/06/13 职场文书
2015年农村党员公开承诺事项
2015/04/28 职场文书