手机
当前位置:查字典教程网 >脚本专栏 >python >Python生成验证码实例
Python生成验证码实例
摘要:本文实例展示了Python生成验证码的方法,具有很好的实用价值。分享给大家供大家参考。具体实现方法如下:前台页面代码如下:看不清换一张fun...

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

前台页面代码如下:

<div> <img id="authcode_img" alt="验证码" src="http://www.jb51.netregistration/makeimage/{{time}}"/> <> <a href="javascript:refreshCode();" rel="external nofollow">看不清换一张</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生成验证码实例1

【Python生成验证码实例】相关文章:

python django集成cas验证系统

Python设计模式之观察者模式实例

Python pass 语句使用示例

python生成器的使用方法

Python实现的几个常用排序算法实例

Python使用urllib2获取网络资源实例讲解

Python MD5文件生成码

python 生成不重复的随机数的代码

python解析json实例方法

python实现的二叉树算法和kmp算法实例

精品推荐
分类导航