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

程序效果如下:

相关文章

OpenCV哈里斯(Harris)角点检测的实现

OpenCV哈里斯(Harris)角点检测的实现

环境 pip install opencv-python==3.4.2.16 pip install opencv-contrib-python==3.4.2.16 理论 克里...

解决python "No module named pip"的问题

python 升级后导致不能使用原来的pip命令 windows平台 cmd中敲命令:python -m ensurepip 得到pip的setuptools 然后就可以用:easy_i...

完美解决Python 2.7不能正常使用pip install的问题

主要原因是用户目录编码使用了中文,解决方法如下: pip安装python包会加载我的用户目录,我的用户目录恰好是中文的,ascii不能编码。 解决办法是: python目录 Pytho...

pytorch中的卷积和池化计算方式详解

pytorch中的卷积和池化计算方式详解

TensorFlow里面的padding只有两个选项也就是valid和same pytorch里面的padding么有这两个选项,它是数字0,1,2,3等等,默认是0 所以输出的h和w的...

python selenium 查找隐藏元素 自动播放视频功能

python selenium 查找隐藏元素 自动播放视频功能

在使用python做爬虫的过程中,有些页面的的部分数据是通过js异步加载的,js调用接口的请求中有时还带有些加密的参数很难破解无法使用requests这样的包直接爬取数据,因此需要借助s...