diff --git a/backend/auth/utils/__pycache__/captcha.cpython-313.pyc b/backend/auth/utils/__pycache__/captcha.cpython-313.pyc index 0596e2c..b75f4cb 100644 Binary files a/backend/auth/utils/__pycache__/captcha.cpython-313.pyc and b/backend/auth/utils/__pycache__/captcha.cpython-313.pyc differ diff --git a/backend/auth/utils/captcha.py b/backend/auth/utils/captcha.py index 7205175..e9aef23 100644 --- a/backend/auth/utils/captcha.py +++ b/backend/auth/utils/captcha.py @@ -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,16 +14,19 @@ def generate_captcha(length: int = 4) -> tuple[str, bytes]: characters = string.digits + string.ascii_uppercase captcha_text = ''.join(random.choices(characters, k=length)) - # 生成验证码图片 - image = ImageCaptcha(width=150, height=50) - image_bytes = image.generate(captcha_text) - - # 将图片转换为字节流 - buffer = BytesIO() - buffer.write(image_bytes.read()) - buffer.seek(0) - - return captcha_text, buffer.getvalue() + try: + # 生成验证码图片 + image = ImageCaptcha(width=150, height=50) + image_bytes = image.generate(captcha_text) + + # 将图片转换为字节流 + buffer = BytesIO() + buffer.write(image_bytes.read()) + 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):