当前位置: 移动技术网 > IT编程>脚本编程>Python > Python生成验证码实例

Python生成验证码实例

2019年06月14日  | 移动技术网IT编程  | 我要评论

tingting5yuetian,柚子树的栽培,魔教浩珉

本文实例展示了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

程序效果如下:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网