Bottle框架中实现验证码生成和验证的示例代码
发布时间:2023-12-23 23:55:28
使用Bottle框架实现验证码生成和验证功能的示例代码:
from bottle import Bottle, request, response
from PIL import Image, ImageDraw, ImageFont
import random
import string
app = Bottle()
# 生成验证码
def generate_captcha(width, height, code_length):
# 创建一个空白图片
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建一个绘制对象
draw = ImageDraw.Draw(image)
# 生成验证码字符串
code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=code_length))
# 设置验证码文本字体
font = ImageFont.truetype('arial.ttf', 50)
# 将验证码字符串绘制到图片中
text_width, text_height = draw.textsize(code, font)
x = (width - text_width) / 2
y = (height - text_height) / 2
draw.text((x, y), code, font=font, fill='black')
# 绘制干扰线
for i in range(5):
x1 = random.randint(0, width)
y1 = random.randint(0, height)
x2 = random.randint(0, width)
y2 = random.randint(0, height)
draw.line([(x1, y1), (x2, y2)], fill='black')
# 返回验证码图片和验证码字符串
return image, code
# 生成验证码图片的API
@app.route('/captcha', method='GET')
def get_captcha():
# 调用生成验证码函数生成验证码图片和验证码字符串
image, code = generate_captcha(200, 80, 4)
# 将验证码字符串保存到session中,以便验证时使用
session_id = request.get_cookie('session_id')
if session_id:
response.set_cookie('captcha', code, path='/', secret=session_id)
# 将验证码图片转换为字节流
byte_stream = io.BytesIO()
image.save(byte_stream, format='PNG')
byte_stream.seek(0)
# 设置返回的Content-Type为image/png,并将字节流作为响应返回
response.content_type = 'image/png'
return byte_stream.read()
# 验证验证码的API
@app.route('/validate', method='POST')
def validate_captcha():
# 获取用户提交的验证码
captcha = request.forms.get('captcha')
# 从session中获取之前生成的验证码
session_id = request.get_cookie('session_id')
saved_captcha = request.get_cookie('captcha', secret=session_id)
# 比较用户提交的验证码和之前生成的验证码
if captcha == saved_captcha:
return '验证码正确'
else:
return '验证码错误'
使用例子:
生成验证码图片:
GET /captcha HTTP/1.1 Host: localhost
返回的响应会包含一个验证码图片。
验证验证码:
POST /validate HTTP/1.1 Host: localhost Content-Type: application/x-www-form-urlencoded captcha=ABCD
其中,captcha参数的值为用户输入的验证码字符串。返回的响应会是"验证码正确"或"验证码错误"。
