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之生产者消费者模型实现详解

代码及注释如下 #Auther Bob #--*--conding:utf-8 --*-- #生产者消费者模型,这里的例子是这样的,有一个厨师在做包子,有一个顾客在吃包子,有一个服务...

详解python路径拼接os.path.join()函数的用法

os.path.join()函数:连接两个或更多的路径名组件 1.如果各组件名首字母不包含'/',则函数会自动加上 demo1 import os Path1 = 'home'...

Python列表与元组的异同详解

前言 “列表(list)与元组(tuple)两种数据类型有哪些区别”这个问题在初级程序员面试中经常碰到,超出面试官预期的答案往往能加不少印象分,也会给后续面试顺利进行提供一定帮助,这道题...

python self,cls,decorator的理解

1. self, cls 不是关键字 在python里面,self, cls 不是关键字,完全可以使用自己写的任意变量代替实现一样的效果 代码1 复制代码 代码如下:class MyTe...

详解Python的Django框架中的通用视图

详解Python的Django框架中的通用视图

通用视图 1. 前言 回想一下,在Django中view层起到的作用是相当于controller的角色,在view中实施的 动作,一般是取得请求参数,再从model中得到数据,再通过数据...