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中使用item()方法遍历字典的例子

Python中使用item()方法遍历字典的例子

Python字典的遍历方法有好几种,其中一种是for...in,这个我就不说明,在Python了几乎随处都可见for...in。下面说的这种遍历方式是item()方法。 item() i...

Python数据结构之单链表详解

本文实例为大家分享了Python数据结构之单链表的具体代码,供大家参考,具体内容如下 # 节点类 class Node(): __slots__=['_item','_next'...

Python递归函数 二分查找算法实现解析

Python递归函数 二分查找算法实现解析

一、初始递归 递归函数:在一个函数里在调用这个函数本身。 递归的最大深度:998 正如你们刚刚看到的,递归函数如果不受到外力的阻止会一直执行下去。但是我们之前已经说过关于函数调用的问题...

从源码解析Python的Flask框架中request对象的用法

from flask import request Flask 是一个人气非常高的Python Web框架,笔者也拿它写过一些大大小小的项目,Flask 有一个特性我非常的喜欢,就是无论...

解析Python中的eval()、exec()及其相关函数

刚好前些天有人提到eval()与exec()这两个函数,所以就翻了下Python的文档。这里就来简单说一下这两个函数以及与它们相关的几个函数,如globals()、locals()和co...