后端代码
首先,在app.py文件中添加以下代码:
import random
import string
import io
from flask import Flask, request, make_response, session
from flask_restful import Api, Resource, reqparse
from PIL import Image, ImageDraw, ImageFont, ImageFilter
app = Flask(__name__)
app.config['SECRET_KEY'] = 'thisisasecretkey'
api = Api(app)
# 生成随机字符串
def generate_verification_code(length=4):
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
# 生成验证码图片
def generate_verification_image(verification_code):
# 验证码图片的尺寸和背景色
size = (100, 50)
bgcolor = (255, 255, 255)
# 创建Image对象
image = Image.new('RGB', size, bgcolor)
# 创建Draw对象
draw = ImageDraw.Draw(image)
# 字体
font_size = 25
font = ImageFont.truetype("arial.ttf", font_size)
# 将验证码绘制到图片上
draw.text((10, 10), verification_code, font=font, fill=(0,