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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python中的startswith和endswith函数使用实例

在Python中有两个函数分别是startswith()函数与endswith()函数,功能都十分相似,startswith()函数判断文本是否以某个字符开始,endswith()函数判...

使用python调用浏览器并打开一个网址的例子

python 打开浏览器,可以做简单的刷网页的小程序。仅供学习,别用非法用途。 python的webbrowser模块支持对浏览器进行一些操作,主要有以下三个方法:复制代码 代码如下:w...

简单了解python变量的作用域

简单了解python变量的作用域

1.效果图: 2.代码 # 作用域 是 对象生效的区域(对象能被使用的区域) # 全局作用域在任意位置可生效 # 局部作用域在函数内生效 c = 20 # 全局变量 def f...

python检测IP地址变化并触发事件

IoT PoC项目中需要展示视频采集源进行wifi切换后(表明视频采集源端发生了移动),接收端观看到的视频的流畅度,以及当接收端进行移动时,检测视频的流畅度,故需要一个模块周期性地探测本...

跟老齐学Python之眼花缭乱的运算符

在计算机高级中语言,运算符是比较多样化的。其实,也都源于我们日常的需要。 算术运算符 前面已经讲过了四则运算,其中涉及到一些运算符:加减乘除,对应的符号分别是:+ - * /,此外,还有...