#shw 导入类型提示模块,用于增强代码可读性和健壮性 import typing #shw 导入时间间隔类,用于定义验证码有效期 from datetime import timedelta #shw 导入Django的缓存模块 from django.core.cache import cache #shw 导入Django的翻译函数 from django.utils.translation import gettext #shw 导入Django的延迟翻译函数,用于在类或模型定义等场景 from django.utils.translation import gettext_lazy as _ #shw 从项目工具模块导入发送邮件的函数 from djangoblog.utils import send_email #shw 定义验证码的生存时间(Time To Live)为5分钟 _code_ttl = timedelta(minutes=5) def send_verify_email(to_mail: str, code: str, subject: str = _("Verify Email")): """发送重设密码验证码 Args: to_mail: 接受邮箱 subject: 邮件主题 code: 验证码 """ #shw 构造邮件的HTML内容,使用国际化字符串,并将验证码动态插入 html_content = _( "You are resetting the password, the verification code is:%(code)s, valid within 5 minutes, please keep it " "properly") % {'code': code} #shw 调用项目通用的邮件发送函数来完成发送 send_email([to_mail], subject, html_content) def verify(email: str, code: str) -> typing.Optional[str]: """验证code是否有效 Args: email: 请求邮箱 code: 验证码 Return: 如果有错误就返回错误str Node: 这里的错误处理不太合理,应该采用raise抛出 否测调用方就需要对error进行处理 """ #shw 从缓存中获取指定邮箱对应的验证码 cache_code = get_code(email) #shw 比较用户输入的验证码和缓存中的验证码是否一致 if cache_code != code: #shw 如果不一致,返回一个翻译后的错误信息字符串 return gettext("Verification code error") def set_code(email: str, code: str): """设置code""" #shw 将验证码存入缓存,键为邮箱,值为验证码,并设置5分钟的过期时间 cache.set(email, code, _code_ttl.seconds) def get_code(email: str) -> typing.Optional[str]: """获取code""" #shw 从缓存中根据邮箱(键)获取验证码(值) return cache.get(email)