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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

利用anaconda保证64位和32位的python共存

背景 喵哥想在MFC中调用python脚本,在原来的代码中包含一个只支持x86的库文件(超级核心的文件),原本安装的python是x64的,强行运行程序会出现python头文件里的函数无...

python使用fork实现守护进程的方法

os模块中的fork方法可以创建一个子进程。相当于克隆了父进程 os.fork() 子进程运行时,os.fork方法会返回0;  而父进程运行时,os.fork方法会返回子进程...

python的常见矩阵运算(小结)

python的numpy库提供矩阵运算的功能,因此我们在需要矩阵运算的时候,需要导入numpy的包。 1.numpy的导入和使用 from numpy import *;#导入nu...

python打印n位数“水仙花数”(实例代码)

注:所谓n位数“水仙花数”是指一个n数,其各位数字n次方和等于该数本身。如三位数“水仙花数”是指一个三位数,其各位数3次方和等于该数本身。 一、3位数“水仙花数”如下: ...

Python机器学习之K-Means聚类实现详解

Python机器学习之K-Means聚类实现详解

本文为大家分享了Python机器学习之K-Means聚类的实现代码,供大家参考,具体内容如下 1.K-Means聚类原理 K-means算法是很典型的基于距离的聚类算法,采用距离作为相...