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) #lht: 验证码有效期5分钟 def send_verify_email(to_mail: str, code: str, subject: str = _("Verify Email")): #lht: """发送重设密码验证码 #lht: Args: #lht: to_mail: 接受邮箱 #lht: subject: 邮件主题 #lht: code: 验证码 #lht: """ 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]: #lht: """验证code是否有效 #lht: Args: #lht: email: 请求邮箱 #lht: code: 验证码 #lht: Return: #lht: 如果有错误就返回错误str #lht: Node: #lht: 这里的错误处理不太合理,应该采用raise抛出 #lht: 否测调用方也需要对error进行处理 #lht: """ cache_code = get_code(email) if cache_code != code: return gettext("Verification code error") def set_code(email: str, code: str): #lht: """设置code""" cache.set(email, code, _code_ttl.seconds) def get_code(email: str) -> typing.Optional[str]: #lht: """获取code""" return cache.get(email)