Django验证码的生成与使用示例


Posted in Python onMay 20, 2017

前言

本文主要介绍的是关于Django验证码生成与使用的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:

方法如下:

1、基于PIL生成一个带验证码的图片和验证码,生成验证码图片需要Monaco.ttf字体,可按自己要求更改check_code中的字体和字体文件位置,如下图

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter

_letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母,去除可能干扰的i,l,o,z
_upper_cases = _letter_cases.upper() # 大写字母
_numbers = ''.join(map(str, range(3, 10))) # 数字
init_chars = ''.join((_letter_cases, _upper_cases, _numbers))


def create_validate_code(size=(120, 30),
       chars=init_chars,
       img_type="GIF",
       mode="RGB",
       bg_color=(255, 255, 255),
       fg_color=(0, 0, 255),
       font_size=18,
       font_type="Monaco.ttf",
       length=4,
       draw_lines=True,
       n_line=(1, 2),
       draw_points=True,
       point_chance=2):
 """
 @todo: 生成验证码图片
 @param size: 图片的大小,格式(宽,高),默认为(120, 30)
 @param chars: 允许的字符集合,格式字符串
 @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG
 @param mode: 图片模式,默认为RGB
 @param bg_color: 背景颜色,默认为白色
 @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF
 @param font_size: 验证码字体大小
 @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf
 @param length: 验证码字符个数
 @param draw_lines: 是否划干扰线
 @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效
 @param draw_points: 是否画干扰点
 @param point_chance: 干扰点出现的概率,大小范围[0, 100]
 @return: [0]: PIL Image实例
 @return: [1]: 验证码图片中的字符串
 """

 width, height = size # 宽高
 # 创建图形
 img = Image.new(mode, size, bg_color)
 draw = ImageDraw.Draw(img) # 创建画笔

 def get_chars():
  """生成给定长度的字符串,返回列表格式"""
  return random.sample(chars, length)

 def create_lines():
  """绘制干扰线"""
  line_num = random.randint(*n_line) # 干扰线条数

  for i in range(line_num):
   # 起始点
   begin = (random.randint(0, size[0]), random.randint(0, size[1]))
   # 结束点
   end = (random.randint(0, size[0]), random.randint(0, size[1]))
   draw.line([begin, end], fill=(0, 0, 0))

 def create_points():
  """绘制干扰点"""
  chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]

  for w in range(width):
   for h in range(height):
    tmp = random.randint(0, 100)
    if tmp > 100 - chance:
     draw.point((w, h), fill=(0, 0, 0))

 def create_strs():
  """绘制验证码字符"""
  c_chars = get_chars()
  strs = ' %s ' % ' '.join(c_chars) # 每个字符前后以空格隔开

  font = ImageFont.truetype(font_type, font_size)
  font_width, font_height = font.getsize(strs)

  draw.text(((width - font_width) / 3, (height - font_height) / 3),
     strs, font=font, fill=fg_color)

  return ''.join(c_chars)

 if draw_lines:
  create_lines()
 if draw_points:
  create_points()
 strs = create_strs()

 # 图形扭曲参数
 params = [1 - float(random.randint(1, 2)) / 100,
    0,
    0,
    0,
    1 - float(random.randint(1, 10)) / 100,
    float(random.randint(1, 2)) / 500,
    0.001,
    float(random.randint(1, 2)) / 500
    ]
 img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲

 img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大)

 return img, strs

check_code.py

Django验证码的生成与使用示例

2、创建urls和views,请按自己需求创建

# 将check_code包放在合适的位置,导入即可,我是放在utils下面
from utils import check_code

def create_code_img(request):
 f = BytesIO() #直接在内存开辟一点空间存放临时生成的图片

 img, code = check_code.create_validate_code() #调用check_code生成照片和验证码
 request.session['check_code'] = code #将验证码存在服务器的session中,用于校验
 img.save(f,'PNG') #生成的图片放置于开辟的内存中
 return HttpResponse(f.getvalue()) #将内存的数据读取出来,并以HttpResponse返回

Views

urls我的设置:url(r'^create_code_img/', views.create_code_img)

3、前端应用验证码和点击自动刷新

<div class="row">
     <div class="col-xs-7">
      <input type="text" class="form-control" name="check_code" id="check_code" placeholder="请输入验证码">
     </div>
     <div class="col-xs-5">
      <img id="check_code_img" src="/create_code_img/" onclick="refresh_check_code(this)">
{#      src是url路径,可得到验证码图片,点击时调用refresh_check_code#}
     </div>
    </div>
<script>
   function refresh_check_code(ths) {
     ths.src += '?';
 {#    src后面加问好会自动刷新验证码img的src#}
   }
  </script>

4、login的Views进行数据验证,然后做相应的处理

post_check_code = request.POST.get('check_code')
session_check_code = request.session['check_code']
if post_check_code.lower() == session_check_code.lower() :
 pass

总结

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
Python BeautifulSoup中文乱码问题的2种解决方法
Apr 22 Python
python基于BeautifulSoup实现抓取网页指定内容的方法
Jul 09 Python
Python 高级专用类方法的实例详解
Sep 11 Python
python opencv之分水岭算法示例
Feb 24 Python
使用python中的in ,not in来检查元素是不是在列表中的方法
Jul 06 Python
python使用pdfminer解析pdf文件的方法示例
Dec 20 Python
python使用wxpy实现微信消息防撤回脚本
Apr 29 Python
python实现身份证实名认证的方法实例
Nov 08 Python
Tensorflow: 从checkpoint文件中读取tensor方式
Feb 10 Python
python GUI库图形界面开发之PyQt5窗口类QMainWindow详细使用方法
Feb 26 Python
python 爬取免费简历模板网站的示例
Sep 27 Python
Python3使用Qt5来实现简易的五子棋小游戏
May 02 Python
Linux RedHat下安装Python2.7开发环境
May 20 #Python
深入理解Python中的内置常量
May 20 #Python
python万年历实现代码 含运行结果
May 20 #Python
关于pip的安装,更新,卸载模块以及使用方法(详解)
May 19 #Python
python通过pip更新所有已安装的包实现方法
May 19 #Python
python django 实现验证码的功能实例代码
May 18 #Python
python实现发送邮件及附件功能
Mar 02 #Python
You might like
PHP ? EasyUI DataGrid 资料取的方式介绍
2012/11/07 PHP
PHP处理excel cvs表格的方法实例介绍
2013/05/13 PHP
浅析PHP中的字符串编码转换(自动识别原编码)
2013/07/02 PHP
PHP连接SQLServer2005方法及代码
2013/12/26 PHP
PHP中字符串长度的截取用法示例
2017/01/12 PHP
javascript标签在页面中的位置探讨
2013/04/11 Javascript
JQuery插件fancybox无法在弹出层使用左右键的解决办法
2013/12/25 Javascript
JS+CSS实现淡入式焦点图片幻灯切换效果的方法
2015/02/26 Javascript
解决angular的post请求后SpringMVC后台接收不到参数值问题的方法
2015/12/10 Javascript
js实现人民币大写金额形式转换
2016/04/27 Javascript
jQuery.uploadify文件上传组件实例讲解
2016/09/23 Javascript
Node.js五大应用性能技巧小结(必须收藏)
2017/08/09 Javascript
利用JavaScript的%做隔行换色的实例
2017/11/25 Javascript
JS基于for语句编写的九九乘法表示例
2018/01/04 Javascript
如何基于vue-cli3.0构建功能完善的移动端架子
2019/04/24 Javascript
浅析vue中的provide / inject 有什么用处
2019/11/10 Javascript
vue+canvas实现移动端手写签名
2020/05/21 Javascript
Python读大数据txt
2016/03/28 Python
python 拼接文件路径的方法
2018/10/23 Python
python ipset管理 增删白名单的方法
2019/01/14 Python
使用python进行广告点击率的预测的实现
2019/07/04 Python
python脚本和网页有何区别
2020/07/02 Python
详解快速开发基于 HTML5 网络拓扑图应用
2018/01/08 HTML / CSS
全球速卖通巴西站点:Aliexpress巴西
2016/08/24 全球购物
国际知名设计师时装商店:Coggles
2016/09/05 全球购物
爱岗敬业演讲稿范文
2014/01/14 职场文书
工作鉴定评语
2014/05/04 职场文书
小学安全汇报材料
2014/08/14 职场文书
关于工作时间玩手机的检讨书
2014/09/18 职场文书
实名检举信范文
2015/03/02 职场文书
2016大学生入党积极分子心得体会
2016/01/06 职场文书
Python中threading库实现线程锁与释放锁
2021/05/17 Python
Python中seaborn库之countplot的数据可视化使用
2021/06/11 Python
Python turtle实现贪吃蛇游戏
2021/06/18 Python
vue-router中hash模式与history模式的区别
2021/06/23 Vue.js
windows系统安装配置nginx环境
2022/06/28 Servers