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在TXT文件中按照某一字符串取出该字符串所在的行方法

主要流程:读取文件数据——将每一行数据分成不同的字符段——在判断 在某个字否段是否含与某个字符。(只是其中一种办法) 代码如下: with open(r"C:\Users\LENOV...

python脚本之一键移动自定格式文件方法实例

python脚本之一键移动自定格式文件方法实例

前言 尝试用python语言写脚本是好的开始,证明我们有了自动化的思想,这对优秀的程序开发人员是很重要的,电子计算机本来就是要减少重复工作的。 首先我们要用到python自带的一些包,p...

django加载本地html的方法

django加载本地html的方法

django加载本地html from django.shortcuts import render from django.http import HttpResponse fro...

给Python入门者的一些编程建议

Python是一种非常富有表现力的语言。它为我们提供了一个庞大的标准库和许多内置模块,帮助我们快速完成工作。然而,许多人可能会迷失在它提供的功能中,不能充分利用标准库,过度重视单行脚本,...

使用python脚本实现查询火车票工具

使用python脚本实现查询火车票工具

使用python脚本实现查询火车票信息的效果图如下: 实现的代码: # coding: utf-8 """命令行火车票查看器 Usage: tickets [-gdtkz] O...