import typing from datetime import timedelta 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 _code_ttl = timedelta(minutes=5) # sjt 验证码有效期(5分钟) def send_verify_email(to_mail: str, code: str, subject: str = _("Verify Email")): '''sjt 发送密码重置验证码邮件 Args: to_mail: 接收邮箱 subject: 邮件主题 code: 验证码 ''' html_content = _( "You are resetting the password, the verification code is:%(code)s, valid within 5 minutes, please keep it " "properly") % {'code': code} send_email([to_mail], subject, html_content) def verify(email: str, code: str) -> typing.Optional[str]: '''sjt 验证验证码有效性 Args: email: 请求邮箱 code: 验证码 Return: 如果有错误返回错误信息字符串,否则返回None ''' cache_code = get_code(email) # sjt 从缓存获取验证码 if cache_code != code: # sjt 验证码不匹配 return gettext("Verification code error") def set_code(email: str, code: str): #sjt 将验证码存入缓存(有效期5分钟) cache.set(email, code, _code_ttl.seconds) def get_code(email: str) -> typing.Optional[str]: #sjt 从缓存获取验证码 return cache.get(email)