我们再python web方向开发,验证码肯定是少不了的,网上down了段代码,自己测试下了,发现有些小问题,但是也都解决了,下面记录下来,方便以后使用
验证码主要函数:
captcha.py
#!/usr/bin/python3 #coding:utf-8 from PIL import Image, ImageFont, ImageDraw, ImageFilter import random def captcha(): total = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789' # 图片大小130 x 50 width = 130 heighth = 50 # 先生成一个新图片对象 im = Image.new('RGB',(width, heighth), 'white') # 设置字体 font = ImageFont.truetype('app/static/font/century.ttf', 40) # 创建draw对象 draw = ImageDraw.Draw(im) str = '' # 输出每一个文字 for item in range(5): text = random.choice(total) str += text draw.text((5+random.randint(4,7)+20*item,5+random.randint(3,7)), text=text, fill='black',font=font ) # 划几根干扰线 for num in range(8): x1 = random.randint(0, width/2) y1 = random.randint(0, heighth/2) x2 = random.randint(0, width) y2 = random.randint(heighth/2, heighth) draw.line(((x1, y1),(x2,y2)), fill='black', width=1) im = im.filter(ImageFilter.FIND_EDGES) return im, str
然后视图函数是这样使用
from flask import Flask,session,make_response from app.captcha import captcha from io import BytesIO @web.route('/captcha') def verify_code(): image, str = captcha() buf = BytesIO() image.save(buf, 'jpeg') buf_str = buf.getvalue() response = make_response(buf_str) response.headers['Content-Type'] = 'image/png' session['verify_code'] = str return response
前端代码式样使用
<img id="verify_vode" class="captcha" src="{{ url_for('web.verify_code') }}" onclick="this.src='/captcha?'+ Math.random()"/>
效果如下