Python生成验证码实例

yipeiwu_com6年前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常见MongoDB数据库操作实例总结

本文实例讲述了Python常见MongoDB数据库操作。分享给大家供大家参考,具体如下: MongoDB 是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的...

Python实现手机号自动判断男女性别(实例解析)

Python实现手机号自动判断男女性别(实例解析)

本文性别判断主要依靠airtest中的自动化测试实现 通过自动对比支付宝页面男女图像,从而实现男女判断 代码如下: 男女判断函数: // An highlighted block...

Python常见工厂函数用法示例

本文实例讲述了Python常见工厂函数用法。分享给大家供大家参考,具体如下: 工厂函数:能够产生类实例的内建函数。  工厂函数是指这些内建函数都是类对象, 当调用它们时,实际上...

python opencv之SIFT算法示例

python opencv之SIFT算法示例

本文介绍了python opencv之SIFT算法示例,分享给大家,具体如下: 目标: 学习SIFT算法的概念 学习在图像中查找SIFT关键的和描述符 原理: (原理部分自己找了不少文...

Python实现购物评论文本情感分析操作【基于中文文本挖掘库snownlp】

Python实现购物评论文本情感分析操作【基于中文文本挖掘库snownlp】

本文实例讲述了Python实现购物评论文本情感分析操作。分享给大家供大家参考,具体如下: 昨晚上发现了snownlp这个库,很开心。先说说我开心的原因。我本科毕业设计做的是文本挖掘,用R...