zoukankan      html  css  js  c++  java
  • django之验证码

    前期准备:python版本:3.6.3

        pycharm专业版

        django:1.11.16版本

        操作系统:Windows

    开始工作:

    1. 安装Pillow版本4.0.0    命令行:pip install Pillow==4.0.0
    2. 定义一个路由用来返回验证码的视图函数: url(r'^verifycode$', Index.verifycode, name='myadmin_verifycode')
    3. 定义视图函数
    4. def verifycode(request):
          #引入绘图模块
          from PIL import Image, ImageDraw, ImageFont
          #引入随机函数模块
          import random
          #定义变量,用于画面的背景色、宽、高
          bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
          width = 100
          height = 30
          #创建画面对象
          im = Image.new('RGB', (width, height), bgcolor)
          #创建画笔对象
          draw = ImageDraw.Draw(im)
          #调用画笔的point()函数绘制噪点
          for i in range(0, 100):
              xy = (random.randrange(0, width), random.randrange(0, height))
              fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
              draw.point(xy, fill=fill)
          #定义验证码的备选值
          # str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
          str1 = '123456789'
          #随机选取4个值作为验证码
          rand_str = ''
          for i in range(0, 4):
              rand_str += str1[random.randrange(0, len(str1))]
          #构造字体对象,注意此处为windows内置字体
          font = ImageFont.truetype('ebrima.ttf', 23)
          #构造字体颜色
          fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
          #绘制4个字
          draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
          draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
          draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
          draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
          #释放画笔
          del draw
          #存入session,用于做进一步验证
          request.session['verifycode'] = rand_str
          #内存文件操作
          import io
          buf = io.BytesIO()
          #将图片保存在内存中,文件类型为png
          im.save(buf, 'png')
          #将内存中的图片数据返回给客户端,MIME类型为图片png
          return HttpResponse(buf.getvalue(), 'image/png')

    5. 模板中使用:

        <img src="{% url 'myadmin_verifycode' %}" onclick="this.src='{% url 'myadmin_verifycode' %}?'+Math.random()+''" >

  • 相关阅读:
    git的冲突解决--git rebase之abort、continue、skip
    iOS 13苹果登录
    mac上python3.x安装 图文详解
    iOS Bezier曲线
    《从零开始学Swift》学习笔记(Day 23)——尾随闭包
    《从零开始学Swift》学习笔记(Day 22)——闭包那些事儿!
    《从零开始学Swift》学习笔记(Day 21)——函数返回值
    《从零开始学Swift》学习笔记(Day 20)——函数中参数的传递引用
    《从零开始学Swift》学习笔记(Day 19)——函数参数传递
    《从零开始学Swift》学习笔记(Day 18)——有几个分支语句?
  • 原文地址:https://www.cnblogs.com/cage0515/p/9989126.html
Copyright © 2011-2022 走看看