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

程序效果如下:

相关文章

对dataframe数据之间求补集的实例详解

python的pandas库,对于dataframe数据,有merge命令可以完成dataframe数据之间的求取交集并集等命令。 若存在df1与df2 ,他们的交集df3=pd.mer...

网易有道2017内推编程题 洗牌(python)

本文实例为大家分享了网易有道2017内推编程题:洗牌,供大家参考,具体内容如下 ''' [编程题] 洗牌 时间限制:1秒 空间限制:32768K 洗牌在生活中十分常见,现在需要写一个程...

web.py 十分钟创建简易博客实现代码

一、web.py简介 web.py是一款轻量级的Python web开发框架,简单、高效、学习成本低,特别适合作为python web开发的入门框架。官方站点:http://webpy....

python使用threading获取线程函数返回值的实现方法

threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。python当前版本的多线程库没有实现优先级、线程组,线程也不能被停止、暂停、恢复、中断。 threading模...

Python里字典的基本用法(包括嵌套字典)

Python里字典的基本用法(包括嵌套字典)

Python字典的基本用法 创建字典: myDict1 = { '薛之谦':'我叫薛之谦', '吴青峰':'我叫吴青峰', '李宇春':'我叫李宇春', '花花':'...