Update utils.py

master
pbskfcgaw 3 months ago
parent d296193fee
commit 786ab85a3d

@ -7,43 +7,58 @@ from django.utils.translation import gettext_lazy as _
from djangoblog.utils import send_email
# 验证码的生存时间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: 验证码
to_mail: 收邮箱地址
subject: 邮件主题默认为"Verify Email"
code: 需要发送的验证码
"""
# 生成邮件HTML内容包含验证码信息并支持国际化
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: 验证码
email: 需要验证的邮箱地址
code: 用户输入的验证码
Return:
如果有错误就返回错误str
Node:
这里的错误处理不太合理应该采用raise抛出
否测调用方也需要对error进行处理
如果验证失败返回错误信息字符串验证成功返回None
Note:
当前错误处理方式不够合理建议改为抛出异常的方式
这样调用方可以通过try-except来处理错误而不是检查返回值
"""
# 从缓存中获取该邮箱对应的验证码
cache_code = get_code(email)
# 比较缓存中的验证码和用户输入的验证码
if cache_code != code:
return gettext("Verification code error")
# 验证成功返回None
def set_code(email: str, code: str):
"""设置code"""
"""将验证码存储到缓存中
Args:
email: 作为缓存键的邮箱地址
code: 需要存储的验证码
"""
cache.set(email, code, _code_ttl.seconds)
def get_code(email: str) -> typing.Optional[str]:
"""获取code"""
return cache.get(email)
"""从缓存中获取验证码
Args:
email: 作为缓存键的邮箱地址
Return:
返回缓存中的验证码如果不存在或已过期则返回None
"""
return cache.get(email)
Loading…
Cancel
Save