mirror of
https://github.com/fastapiadmin/FastapiAdmin.git
synced 2026-09-20 20:39:55 +00:00
优化代码,下线文件服务模块、分析页
This commit is contained in:
@@ -1,73 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from fastapi import APIRouter, BackgroundTasks, Depends, File, Query, Request, UploadFile
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
|
||||
from app.core.logger import logger
|
||||
from app.api.v1.services.common.common_service import CommonService
|
||||
from app.common.response import SuccessResponse, StreamResponse
|
||||
from app.core.dependencies import AuthPermission
|
||||
from app.core.router_class import OperationLogRoute
|
||||
|
||||
|
||||
router = APIRouter(route_class=OperationLogRoute)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/list',
|
||||
summary="获取文件列表",
|
||||
description="获取文件列表",
|
||||
dependencies=[Depends(AuthPermission(permissions=['common:file:query']))]
|
||||
)
|
||||
async def common_get_file_list(request: Request)->JSONResponse:
|
||||
"""
|
||||
获取文件列表
|
||||
"""
|
||||
file_result = await CommonService.get_file_list_services(request)
|
||||
return SuccessResponse(msg='获取文件列表成功', data=file_result)
|
||||
|
||||
@router.post(
|
||||
'/upload',
|
||||
summary="上传文件",
|
||||
description="上传文件",
|
||||
dependencies=[Depends(AuthPermission(permissions=['common:file:upload']))]
|
||||
)
|
||||
async def common_upload(
|
||||
request: Request,
|
||||
file: UploadFile = File(...)
|
||||
) -> JSONResponse:
|
||||
upload_result = await CommonService.upload_service(request, file)
|
||||
logger.info(f"上传文件成功: {file.filename}")
|
||||
return SuccessResponse(msg='上传成功', data=upload_result)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/download',
|
||||
summary="下载文件",
|
||||
description="下载文件",
|
||||
dependencies=[Depends(AuthPermission(permissions=['common:file:download']))]
|
||||
)
|
||||
async def common_download(
|
||||
background_tasks: BackgroundTasks,
|
||||
file_name: str = Query(alias='fileName'),
|
||||
delete: bool = Query(),
|
||||
) -> StreamingResponse:
|
||||
download_result = await CommonService.download_services(background_tasks, file_name, delete)
|
||||
logger.info(f"下载文件成功: {file_name}")
|
||||
|
||||
return StreamResponse(msg='下载成功', data=download_result)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/download/resource',
|
||||
summary="下载资源",
|
||||
description="下载资源",
|
||||
dependencies=[Depends(AuthPermission(permissions=['common:file:download']))]
|
||||
)
|
||||
async def common_download_resource(
|
||||
resource: str = Query()
|
||||
) -> StreamingResponse:
|
||||
download_resource_result = await CommonService.download_resource_services(resource)
|
||||
logger.info(f"下载资源成功: {resource}")
|
||||
|
||||
return StreamResponse(msg='下载成功', data=download_resource_result.result)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class UploadResponseSchema(BaseModel):
|
||||
"""
|
||||
上传响应模型
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
file_path: Optional[str] = Field(default=None, description='新文件映射路径')
|
||||
file_name: Optional[str] = Field(default=None, description='新文件名称')
|
||||
origin_name: Optional[str] = Field(default=None, description='原文件名称')
|
||||
file_url: Optional[str] = Field(default=None, description='新文件访问地址')
|
||||
|
||||
|
||||
class FileListResponseSchema(BaseModel):
|
||||
"""
|
||||
获取文件列表返回模型
|
||||
"""
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
name: Optional[str] = Field(default=None, description='文件名称')
|
||||
type: Optional[str] = Field(default=None, description='文件类型')
|
||||
size: Optional[int] = Field(default=None, description='文件大小')
|
||||
modified_time: Optional[str] = Field(default=None, description='文件修改时间')
|
||||
@@ -1,90 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, Generator, List
|
||||
from fastapi import BackgroundTasks, Request, UploadFile
|
||||
|
||||
from app.config.setting import settings
|
||||
from app.core.exceptions import CustomException
|
||||
from app.api.v1.schemas.common.common_schema import UploadResponseSchema, FileListResponseSchema
|
||||
from app.utils.upload_util import UploadUtil
|
||||
|
||||
|
||||
class CommonService:
|
||||
"""通用模块服务层"""
|
||||
|
||||
@classmethod
|
||||
async def get_file_list_services(cls, request: Request) -> List[Dict]:
|
||||
"""获取文件列表service"""
|
||||
file_list_tree = UploadUtil.get_file_tree(settings.PROFILES_ROOT)
|
||||
file_list = []
|
||||
for item in file_list_tree:
|
||||
file_list.append(FileListResponseSchema(
|
||||
name=item.name,
|
||||
type='directory' if item.is_dir() else 'file',
|
||||
size=item.stat().st_size if item.is_file() else None,
|
||||
modified_time=datetime.fromtimestamp(item.stat().st_mtime).isoformat()
|
||||
).model_dump())
|
||||
return file_list
|
||||
|
||||
@classmethod
|
||||
async def upload_service(cls, request: Request, file: UploadFile) -> Dict:
|
||||
"""
|
||||
通用上传service
|
||||
:param request: Request对象
|
||||
:param file: 上传文件对象
|
||||
:return: 上传结果字典
|
||||
"""
|
||||
filename, filepath = await UploadUtil.upload_file(file)
|
||||
|
||||
return UploadResponseSchema(
|
||||
file_path=f'{filepath}',
|
||||
file_name=filename,
|
||||
origin_name=file.filename,
|
||||
file_url=f'{request.base_url}{filepath}',
|
||||
).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def download_services(cls, file_name: str) -> Generator:
|
||||
"""
|
||||
下载下载目录文件service
|
||||
|
||||
:param background_tasks: 后台任务对象
|
||||
:param file_name: 下载的文件名称
|
||||
:param delete: 是否在下载完成后删除文件
|
||||
:return: 文件二进制流
|
||||
"""
|
||||
if '..' in file_name:
|
||||
raise CustomException(msg='文件名称不合法')
|
||||
|
||||
filepath = settings.DOWNLOAD_FILE_PATH.joinpath(file_name)
|
||||
if not UploadUtil.check_file_exists(filepath):
|
||||
raise CustomException(msg='文件不存在')
|
||||
|
||||
return UploadUtil.generate_file(filepath)
|
||||
|
||||
@classmethod
|
||||
async def download_resource_services(cls, resource: str) -> Generator:
|
||||
"""
|
||||
下载上传目录文件service
|
||||
:param resource: 下载的文件路径
|
||||
:return: 文件二进制流
|
||||
"""
|
||||
filepath = Path(resource).joinpath(settings.UPLOAD_FILE_PATH)
|
||||
filename = filepath.name
|
||||
|
||||
if '..' in filename:
|
||||
raise CustomException(msg='文件名称不合法')
|
||||
|
||||
if not all([
|
||||
UploadUtil.check_file_timestamp(filename),
|
||||
UploadUtil.check_file_machine(filename),
|
||||
UploadUtil.check_file_random_code(filename)
|
||||
]):
|
||||
raise CustomException(msg='文件名称不合法')
|
||||
|
||||
if not UploadUtil.check_file_exists(filepath):
|
||||
raise CustomException(msg='文件不存在')
|
||||
|
||||
return UploadUtil.generate_file(filepath)
|
||||
@@ -9,8 +9,7 @@ from app.core.exceptions import CustomException
|
||||
from app.core.hash_bcrpy import PwdUtil
|
||||
from app.api.v1.cruds.system.position_crud import PositionCRUD
|
||||
from app.api.v1.cruds.system.role_crud import RoleCRUD
|
||||
from app.api.v1.schemas.common.common_schema import UploadResponseSchema
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.base_schema import BatchSetAvailable, UploadResponseSchema
|
||||
from app.utils.excel_util import ExcelUtil
|
||||
from app.utils.upload_util import UploadUtil
|
||||
from app.api.v1.cruds.system.user_crud import UserCRUD
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from fastapi import APIRouter
|
||||
from app.api.v1.controllers.common.common_controller import router as CommonRouter
|
||||
|
||||
|
||||
CommonApiRouter = APIRouter(prefix="/common")
|
||||
|
||||
|
||||
CommonApiRouter.include_router(router=CommonRouter, prefix="/file", tags=["文件模块"])
|
||||
Reference in New Issue
Block a user