feat(routers): 完善auth、card、file、user相关接口开发

This commit is contained in:
xingc
2025-02-22 11:38:56 +08:00
parent 02ddc81c51
commit 1b2f9c7539
11 changed files with 573 additions and 123 deletions

View File

@@ -6,25 +6,30 @@
# @Desc :
import hashlib
import logging
import os
from io import BytesIO
from pathlib import Path
from typing import Literal
from urllib.parse import urljoin
from fastapi import APIRouter, UploadFile, File, status, HTTPException, Depends
from PIL import Image
from config import settings
from . import schema
from core.base.schema import BaseResponse
from core.routers.auth.schema import LoginUser
from core.routers.auth.services import get_current_user
from . import schema
logger = logging.getLogger(__name__)
file_router = APIRouter(prefix='/file', tags=['文件存储模块'])
@file_router.post('/{upload_type}/upload', response_model=BaseResponse[schema.FileOut])
@file_router.post('/{upload_type}/upload', summary='图片上传', response_model=BaseResponse[schema.FileOut])
async def upload_file(
upload_type: Literal['card', 'chat', 'avatar'],
file: UploadFile = File(...)
file: UploadFile = File(...),
login_user: LoginUser = Depends(get_current_user)
):
# 验证文件类型
if file.content_type not in settings.UPLOADED_ALLOWED_MIME_TYPES:
@@ -44,15 +49,12 @@ async def upload_file(
file_chunks = await file.read()
file_hash = hashlib.sha256(file_chunks).hexdigest()
file_name = f'{file_hash}.jpg'
dirname_args = [settings.UPLOADED_FILES_DIR, upload_type.lower()]
if upload_type.lower() != 'card':
dirname_args.append('test')
dirname_args = [upload_type.lower(), str(login_user.user_id), file_name]
save_path = os.path.join(*dirname_args)
save_file_path = os.path.join(*dirname_args, file_name)
if os.path.exists(save_file_path) is False:
save_file_path: Path = settings.UPLOADED_FILES_DIR.joinpath(*dirname_args)
if save_file_path.exists() is False:
# 创建目录
os.makedirs(save_path, exist_ok=True)
save_file_path.parent.mkdir(parents=True, exist_ok=True)
img = Image.open(BytesIO(file_chunks))
img = img.convert("RGB")
@@ -61,9 +63,9 @@ async def upload_file(
file_info = {
'filename': file_name,
'content_type': file.content_type,
'size': os.path.getsize(save_path),
'size': file.size,
'hash': file_hash,
'url': save_file_path
'url': urljoin(settings.ASSETS_BASE_URL, '/'.join([settings.UPLOADED_FILES_DIR.name, *dirname_args])),
}
return {'data': file_info}