Django框架验证码用法实例分析


Posted in Python onMay 10, 2019

本文实例讲述了Django框架验证码用法。分享给大家供大家参考,具体如下:

验证码

1、作用

  • 在用户登录,注册以及一些敏感操作的时候,我们为了防止服务器被暴力请求,或爬虫爬取,我们可以使用验证码进行过滤,减轻服务器的压力。
  • 验证码需要使用绘图 Pillow
    • pip3 install Pillow
    • 核心API
    • Image
      • 需要模式
      • 尺寸
      • 背景色
    • ImageDraw
      • 绑定画布
      • 模式
      • 封装了绘制的API
      • text
      • point
      • line
      • arch
    • ImageFont
      • 手动指定字体

2、业务流程

绘制验证码图片

background = (10,20,30) // RGB颜色

初始化画布

image = Image.new(‘RGB',(100,50),background)

获取画布中画笔对象

draw = ImageDraw.Draw(image)

绘制验证码,随机四个

font = ImageFont.truetype(‘path',size)
fontcolor = (20,40,60)
draw.text((x,y),'R',font,fontcolor)

返回验证码内容

# 删除画笔
del draw
#保存图片到BytesIO对象
Import io
buf = io.BytesIO()
image.save(buf,'png')
#返回BytesIO中的内容
return HttpResponse(buf.getvalue(),'image/png')

3、代码范例

html页面

<form method="post" action="{% url 'sitesApp:login' %}">
  {% csrf_token %}
    <div class="login">
      <div class="input-group">
       <span class="input-group-addon" id="basic-addon1">用户名</span>
       <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1" name="uName">
      </div>
      <div class="input-group">
       <span class="input-group-addon" id="basic-addon1">密    码</span>
       <input type="text" class="form-control" placeholder="Password" aria-describedby="basic-addon1" name="uPswd">
      </div>
      <div class="input-group">
       <span class="input-group-addon" id="basic-addon1">验证码</span>
       <input type="text" class="form-control" placeholder="Auth code" aria-describedby="basic-addon1" name="uCode">
      </div>
      <div class="vcode">
        <img src="/app/getvcode/" id="vcode">
      </div>
      <input type="submit" class="loginBtn" value="登 录"><br>
    </div>
  </form>
  <script type="text/javascript">
    $(function () {
      $('#vcode').click(function () {
        $(this).attr('src',"/app/getvcode"+Math.random())
      })
    })
  </script>

views视图

'''
生成并返回验证码
'''
def getvcode(request):
  # 随机生成验证码
  population = string.ascii_letters+string.digits
  letterlist = random.sample(population,4)
  vcode = ''.join(letterlist)
  # 保存该用户的验证码
  request.session['vcode']=vcode
  # 绘制验证码
  # 需要画布,长宽颜色
  image = Image.new('RGB',(176,60),color=getRandomColor())
  # 创建画布的画笔
  draw = ImageDraw.Draw(image)
  # 绘制文字,字体所在位置
  path = os.path.join(BASE_DIR,'static','fonts','ADOBEARABIC-BOLDITALIC.OTF')
  font = ImageFont.truetype(path,50)
  for i in range(len(vcode)):
    draw.text((20+40*i,0),vcode[i],fill=getRandomColor(),font=font)
  # 添加噪声
  for i in range(500):
    position = (random.randint(0,176),random.randint(0,50))
    draw.point(position,fill=getRandomColor())
  # 返回验证码字节数据
  # 创建字节容器
  buffer = io.BytesIO()
  # 将画布内容丢入容器
  image.save(buffer,'png')
  # 返回容器内的字节
  return HttpResponse(buffer.getvalue(),'image/png')
# 获取随机颜色
def getRandomColor():
  red = random.randint(0,255)
  green = random.randint(0,255)
  blue = random.randint(0,255)
  return (red,green,blue)

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

Python 相关文章推荐
开始着手第一个Django项目
Jul 15 Python
Python的Django框架中的Context使用
Jul 15 Python
Python实现简单的四则运算计算器
Nov 02 Python
python利用Guetzli批量压缩图片
Mar 23 Python
python 打印直角三角形,等边三角形,菱形,正方形的代码
Nov 21 Python
1 行 Python 代码快速实现 FTP 服务器
Jan 25 Python
python3实现指定目录下文件sha256及文件大小统计
Feb 25 Python
Python实现Singleton模式的方式详解
Aug 08 Python
Python中函数的返回值示例浅析
Aug 28 Python
python实现3D地图可视化
Mar 25 Python
python使用隐式循环快速求和的实现示例
Sep 11 Python
python中最小二乘法详细讲解
Feb 19 Python
Python爬虫实现验证码登录代码实例
May 10 #Python
详解如何管理多个Python版本和虚拟环境
May 10 #Python
不到40行代码用Python实现一个简单的推荐系统
May 10 #Python
Python和Java的语法对比分析语法简洁上python的确完美胜出
May 10 #Python
Python3列表内置方法大全及示例代码小结
May 10 #Python
详解python 爬取12306验证码
May 10 #Python
详解用python写一个抽奖程序
May 10 #Python
You might like
PHP生成随机数的方法实例分析
2015/01/22 PHP
php数组键值用法实例分析
2015/02/27 PHP
制作高质量的JQuery Plugin 插件的方法
2010/04/20 Javascript
JavaScript 继承使用分析
2011/05/12 Javascript
Extjs4中的分页应用结合前后台
2013/12/13 Javascript
JavaScript语言对Unicode字符集的支持详解
2014/12/30 Javascript
JavaScript的内存释放问题详解
2015/01/21 Javascript
js实现具有高亮显示效果的多级菜单代码
2015/09/01 Javascript
z-blog SyntaxHighlighter 长代码无法换行解决办法(基于jquery)
2015/11/18 Javascript
理解javascript中try...catch...finally
2015/12/25 Javascript
jQuery实现简单的点赞效果
2020/05/29 Javascript
js禁止表单重复提交
2017/08/29 Javascript
理解 JavaScript EventEmitter
2018/03/29 Javascript
详解Webstorm 下的Angular2.0开发之路(图文)
2018/12/06 Javascript
vue中的过滤器实例代码详解
2019/06/06 Javascript
express框架下使用session的方法
2019/07/31 Javascript
[43:33]EG vs Spirit Supermajor 败者组 BO3 第一场 6.4
2018/06/05 DOTA
Python的动态重新封装的教程
2015/04/11 Python
Windows 7下Python Web环境搭建图文教程
2018/03/20 Python
Tensorflow加载预训练模型和保存模型的实例
2018/07/27 Python
python hook监听事件详解
2018/10/25 Python
css3实现信纸/同学录效果的示例代码
2018/12/11 HTML / CSS
HTML5是什么 HTML5是什么意思 HTML5简介
2012/10/26 HTML / CSS
德国汉莎航空中国官网: Lufthansa中国
2017/03/30 全球购物
李宁官方网店:中国运动品牌
2017/11/02 全球购物
爱尔兰领先的在线体育用品零售商:theGAAstore
2018/04/16 全球购物
来自世界上最好大学的在线课程:edX
2018/10/16 全球购物
护理自我鉴定范文
2013/10/06 职场文书
公司培训心得体会
2014/01/03 职场文书
新年爱情寄语
2014/04/08 职场文书
三好学生演讲稿范文
2014/04/26 职场文书
2015年清明节演讲稿范文
2015/03/17 职场文书
父亲去世追悼词
2015/06/23 职场文书
运动会加油稿
2015/07/22 职场文书
公司开业的祝贺语大全(60条)
2019/07/05 职场文书
Python集合set()使用的方法详解
2022/03/18 Python