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设计】。

相关文章

浅析Python3中的对象垃圾收集机制

###概述 GC作为现代编程语言的自动内存管理机制,专注于两件事:1. 找到内存中无用的垃圾资源 2. 清除这些垃圾并把内存让出来给其他对象使用。 在Python中,它在每个对象中保持了...

python实现支付宝转账接口

python实现支付宝转账接口

由于工作需要使用python开发一个自动转账接口,记录一下开发过程。 首先需要在蚂蚁金服上申请开通开发者账户,有了开发者账户就可以使用沙箱进行开发了。 在开发之前我们需要在沙箱应用中填写...

浅析pandas 数据结构中的DataFrame

浅析pandas 数据结构中的DataFrame

DataFrame 类型类似于数据库表结构的数据结构,其含有行索引和列索引,可以将DataFrame 想成是由相同索引的Series组成的Dict类型。在其底层是通过二维以及一维的数据块...

Python生成随机验证码的两种方法

使用python生成随机验证码的方法有很多种,今天小编给大家分享两种方法,大家可以灵活运用这两种方法,设计出适合自己的验证码方法。 方法一: 利用range方法,对于range方法不清楚...

Python下使用Psyco模块优化运行速度

今天介绍下Psyco模块,Psyco模块可以使你的Python程序运行的像C语言一样快。 都说Python语言易用易学,但性能上跟一些编译语言(如C语言)比较要差不少,这里可以用C语言和...