Python生成验证码实例

yipeiwu_com5年前Python基础

本文实例展示了Python生成验证码的方法,具有很好的实用价值。分享给大家供大家参考。具体实现方法如下:

前台页面代码如下:

<div>
 <img id="authcode_img" alt="验证码" src="/registration/makeimage/{{time}}"/>  
 <!-- time 任意随机数(时间戳),防止页面缓存 导致验证码不能更新-->
 <a href="javascript:refreshCode();" rel="external nofollow" style="color:blue;">看不清换一张</a>
</div>

<script>
 function refreshCode() {
   $('authcode_img').src = "/registration/makeimage/" + Math.random();
 }
</script>

后台程序如下:

import StringIO
import Image, ImageDraw, ImageFont, random  #相应的模块需要安装
from xxx.settings import authcode_font #请确保改字体存在

def make_image(request):
  mp = hashlib.md5()
  mp.update(str(datetime.datetime.now())+str(random.random()))  
  mp_src = mp.hexdigest()
  rand_str = mp_src[0:6]
  font = ImageFont.truetype(authcode_font, 25)
  width = 75
  height = 30
  im = Image.new('RGB',(width,height),'#%s'%mp_src[-7:-1])
  draw = ImageDraw.Draw(im)
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.line((random.randint(0,width),random.randint(0,height),random.randint(0,width),random.randint(0,height)))
  draw.text((5,2), rand_str, font=font)  
  del draw  
  buffer = StringIO.StringIO()
  im.save(buffer,'jpeg')
  httpResponse = HttpResponse(content=buffer.getvalue(),mimetype="image/jpeg")
  request.session['auth_code'] = rand_str
  return httpResponse

程序效果如下:

相关文章

Python脚本获取操作系统版本信息

Python脚本获取操作系统版本信息

查看系统版本信息是一件家常便饭的事情,有时候需要将版本信息录入到资产管理系统中,如果每次手动的去查询这些信息再录入系统那么是一件令人呢头疼的事情,如果采用脚本去完成这件事情,那么情况就有...

python实现用户登陆邮件通知的方法

本文实例讲述了python实现用户登陆邮件通知的方法。分享给大家供大家参考。具体如下: 这里写在linux计划任务里定时执行,当有新用户登陆时候发送用户名到指定邮箱通知管理员。 #!...

python创建和使用字典实例详解

字典是python中唯一内建的映射类型。字典中的值并没有特殊的顺序,但是都存储在一个特定的键(key)里。键可以是数字,字符串甚至是元组。1. 创建和使用字典字典可以通过下面的方式创建:...

利用python和百度地图API实现数据地图标注的方法

利用python和百度地图API实现数据地图标注的方法

如题,先上效果图: 主要分为两大步骤 使用python语句,通过百度地图API,对已知的地名抓取经纬度 使用百度地图API官网的html例程,修改数据部分,实现呈现效果 一、使用pyt...

Python SQLite3数据库操作类分享

接触Python时间也不是很长的,最近有个项目需要分析数据,于是选用Python为编程语言,除了语言特性外主要还是看重Python对于SQLite3数据库良好的支持能力了,因为需要灵活处...