redis实现图形验证码的存储和验证

生成图形验证码

import random
import string
import uuid
from captcha.image import ImageCaptcha

# 连接Redis,相当于redis.Redis()    暂时是本地连接,decode_responses=True是将redis读取出来的短信验证码转换成字符串类型,原本是二进制字节
redis_client = redis.StrictRedis(host=SMS_REDIS_HOST, port=SMS_REDIS_PORT, db=SMS_REDIS_DB, decode_responses=True)

def get_captcha():
    captcha_id = str(uuid.uuid4())
    image = ImageCaptcha()
    _string = string.ascii_letters + string.digits
    captcha_value = ''.join(random.sample(_string, 4))
    data = image.generate(captcha_value, format="webp")
    # 将uuid和验证码字符存储redis中, 60秒过期时间
    redis_client.set(captcha_id, captcha_value, 60)
    # 返回uuid和验证码图像
    return captcha_id, data.getvalue()

验证图形验证码

def verify_captcha(captcha_id, captcha_value):
    value = redis_client.get(captcha_id)
    if value is None or value != captcha_value:
        print("验证码无效!")

你可能感兴趣的:(python,redis,图形验证码)