# 导入类型提示模块 import typing # 导入时间间隔类 from datetime import timedelta # 导入Django缓存框架 from django.core.cache import cache # 导入国际化翻译函数 from django.utils.translation import gettext # 导入延迟翻译函数 from django.utils.translation import gettext_lazy as _ # 导入发送邮件的工具函数 from djangoblog.utils import send_email # 验证码有效期:5分钟 _code_ttl = timedelta(minutes=5) def send_verify_email(to_mail: str, code: str, subject: str = _("Verify Email")): """发送验证邮件,用于密码重置等场景 Args: to_mail: 接收邮件的邮箱地址 subject: 邮件主题,默认为"验证邮箱" code: 验证码内容 """ # 构建邮件HTML内容,包含验证码信息 html_content = _( # 翻译文本:您正在重置密码,验证码是:{code},5分钟内有效,请妥善保管 "You are resetting the password, the verification code is:%(code)s, valid within 5 minutes, please keep it " "properly" ) % {'code': code} # 将code插入到格式化字符串中 # 调用发送邮件函数 send_email([to_mail], subject, html_content) def verify(email: str, code: str) -> typing.Optional[str]: """验证验证码是否有效 Args: email: 请求验证的邮箱地址 code: 用户输入的验证码 Return: 如果验证失败返回错误信息字符串,验证成功返回None Note: 这里的错误处理不太合理,应该采用raise抛出异常 否则调用方也需要对error进行处理 """ # 从缓存中获取该邮箱对应的验证码 cache_code = get_code(email) # 比较缓存中的验证码和用户输入的验证码 if cache_code != code: # 如果不匹配,返回错误信息 return gettext("Verification code error") # 验证成功,返回None def set_code(email: str, code: str): """将验证码设置到缓存中""" # 使用cache.set方法,key为邮箱,value为验证码,设置过期时间 cache.set(email, code, _code_ttl.seconds) def get_code(email: str) -> typing.Optional[str]: """从缓存中获取验证码""" # 使用cache.get方法,根据邮箱获取验证码 return cache.get(email)