You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
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 )
# 验证邮件发送函数 - 向指定邮箱发送验证码邮件
def send_verify_email ( to_mail : str , code : str , subject : str = _ ( " Verify Email " ) ) :
""" 发送重设密码验证码
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 ] :
""" 验证code是否有效
Args:
email: 请求邮箱
code: 验证码
Return:
如果有错误就返回错误str
Node:
这里的错误处理不太合理, 应该采用raise抛出
否测调用方也需要对error进行处理
"""
cache_code = get_code ( email )
if cache_code != code :
return gettext ( " Verification code error " )
# 验证码存储函数 - 将验证码保存到缓存系统
def set_code ( email : str , code : str ) :
""" 设置code """
cache . set ( email , code , _code_ttl . seconds )
# 验证码获取函数 - 从缓存系统中获取验证码
def get_code ( email : str ) - > typing . Optional [ str ] :
""" 获取code """
return cache . get ( email )