refactor: 主要功能实现
目前的工作已经实现的功能: - 基本 FastAPI 路由; - 基本 AI 聊天和创作功能; - 用户信息管理、权限验证、JWT 令牌签发和验证、端点保护; - HTML 验证码邮件发送和验证码验证。
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import logging
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import aiofiles
|
||||
from fastapi import UploadFile
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
UPLOAD_DIR = Path.cwd() / ".nyahome" / "contents"
|
||||
|
||||
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif"}
|
||||
|
||||
|
||||
def s_get_safe_filename(original_name: str) -> str:
|
||||
"""
|
||||
使用 uuid4 生成一个安全的文件名。
|
||||
|
||||
Args:
|
||||
original_name: 完整的原始文件名。
|
||||
|
||||
Raises:
|
||||
TypeError: 拓展名不在允许列表内。
|
||||
|
||||
Returns:
|
||||
uuid4 生成的安全的文件名,后缀不变
|
||||
"""
|
||||
suffix = original_name.rsplit(".", maxsplit=1)[-1]
|
||||
if suffix not in ALLOWED_EXTENSIONS:
|
||||
raise TypeError(f"给定文件的拓展名 {suffix} 不被允许。允许的文件拓展名:{ALLOWED_EXTENSIONS}")
|
||||
return f"{uuid.uuid4().hex}.{suffix}"
|
||||
|
||||
|
||||
async def s_save_upload_file(filename: Path, file: UploadFile) -> None:
|
||||
try:
|
||||
async with aiofiles.open(filename, mode="wb") as f:
|
||||
await f.write(await file.read())
|
||||
logger.info(f"保存文件:{filename.name}")
|
||||
except Exception as e:
|
||||
logger.error(f"保存文件失败:{filename.name}")
|
||||
raise TypeError("保存文件时遇到未知错误,请检查。") from e
|
||||
finally:
|
||||
await file.close()
|
||||
Reference in New Issue
Block a user