fix(auth): 添加验证码生成异常处理

捕获验证码生成过程中的异常并抛出HTTP异常,提高系统健壮性
This commit is contained in:
jayhgq 2026-04-28 17:51:58 +08:00
parent c98adab6ce
commit b9150c3e29
2 changed files with 14 additions and 10 deletions

View File

@ -5,6 +5,7 @@ from utils.redis_client import get_redis, set_token_in_redis
import redis.asyncio as redis
import random
import string
from fastapi import HTTPException
def generate_captcha(length: int = 4) -> tuple[str, bytes]:
@ -13,6 +14,7 @@ def generate_captcha(length: int = 4) -> tuple[str, bytes]:
characters = string.digits + string.ascii_uppercase
captcha_text = ''.join(random.choices(characters, k=length))
try:
# 生成验证码图片
image = ImageCaptcha(width=150, height=50)
image_bytes = image.generate(captcha_text)
@ -23,6 +25,8 @@ def generate_captcha(length: int = 4) -> tuple[str, bytes]:
buffer.seek(0)
return captcha_text, buffer.getvalue()
except Exception as e:
raise HTTPException(status_code=500, detail="验证码生成失败")
async def save_captcha_to_redis(redis_conn: redis.Redis, captcha_id: str, captcha_text: str, expire_seconds: int = 300):