python如何生成网页验证码

yipeiwu_com6年前Python基础

本文实例为大家分享了python生成网页验证码的具体代码,供大家参考,具体内容如下

验证码为pil模块生成,可直接应用于django框架当中。

首先需要安装Pillow模块 我们这里使用的版本为3.4.1
终端中直接输入指令 pip install Pillow==3.4.1

from PIL import Image, ImageDraw, ImageFont
from django.utils.six import BytesIO

def verify_code(request):
  #引入随机函数模块
  import random
  #定义变量,用于画面的背景色、宽、高
  bgcolor = (random.randrange(20, 100), random.randrange(
    20, 100), 255)
  width = 100
  height = 25
  #创建画面对象
  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'
  #随机选取4个值作为验证码
  rand_str = ''
  for i in range(0, 4):
    rand_str += str1[random.randrange(0, len(str1))]
  #构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
  font = ImageFont.truetype('FreeMono.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
  #内存文件操作
  buf = BytesIO()
  #将图片保存在内存中,文件类型为png
  im.save(buf, 'png')
  #将内存中的图片数据返回给客户端,MIME类型为图片png
  return HttpResponse(buf.getvalue(), 'image/png'

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

基于Python中isfile函数和isdir函数使用详解

Python编程语言判断是否是目录 在Python编程语言中可以使用os.path.isdir()函数判断某一路径是否为目录。其函数原型如下所示。 os.path.isdir(pat...

python读取中文txt文本的方法

对于python2.7 字符串在Python2.7内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码成unicode,...

Python排序搜索基本算法之希尔排序实例分析

Python排序搜索基本算法之希尔排序实例分析

本文实例讲述了Python排序搜索基本算法之希尔排序。分享给大家供大家参考,具体如下: 希尔排序是插入排序的扩展,通过允许非相邻的元素进行交换来提高执行效率。希尔排序最关键的是选择步长,...

Python解析并读取PDF文件内容的方法

Python解析并读取PDF文件内容的方法

本文实例讲述了Python解析并读取PDF文件内容的方法。分享给大家供大家参考,具体如下: 一、问题描述 利用python,去读取pdf文本内容。 二、效果 三、运行环境 pytho...

python 循环数据赋值实例

python在数值赋值的时候可以采用数值内循环赋值,很方便 如下 a = [x for x in range(10)] 这样 a = [0,1,2,3,4,5,6,7,8,9]...