接上回,上次和大家简单的介绍了下web验证码实现,也说了异步刷新验证码的实现逻辑,不过有些小伙伴还是建议我实现下,废话少说,上代码:
此代码是需要依赖:
sanic19.9.0
Pillow7.0.0
import random
import string
import uuid
import base64
import platform
from PIL import Image, ImageDraw,ImageFont
from io import BytesIO
from sanic import Sanic
from sanic.response import HTTPResponse,text, json
from sanic.views import HTTPMethodView
app = Sanic()
session = {}
class VerifyCode:
def __init__(self, numbers:int):
"""
指定:生成的数量
"""
self.number = numbers
def draw_lines(self, draw, num, width, height):
"""划线"""
x1 = random.randint(0, width / 2)
y1 = random.randint(0, height / 2)
x2 = random.randint(0, width)
y2 = random.randint(height / 2, height)
draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
def random_color(self):
"""随机颜色"""
return random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)
def gene_text(self):
"""生成验证码"""
return "".join(random.sample(string.ascii_letters+string.digits, self.number))
def get_verify_code(self):
"""
draw.text():
文字的绘制,第一个参数指定绘制的起始点(文本的左上角所在