perf: 优化通用模块service层及异常处理
This commit is contained in:
@@ -10,44 +10,23 @@ commonController = APIRouter(prefix='/common', dependencies=[Depends(LoginServic
|
|||||||
|
|
||||||
@commonController.post("/upload")
|
@commonController.post("/upload")
|
||||||
async def common_upload(request: Request, file: UploadFile = File(...)):
|
async def common_upload(request: Request, file: UploadFile = File(...)):
|
||||||
try:
|
upload_result = await CommonService.upload_service(request, file)
|
||||||
upload_result = await CommonService.upload_service(request, file)
|
logger.info('上传成功')
|
||||||
if upload_result.is_success:
|
|
||||||
logger.info('上传成功')
|
return ResponseUtil.success(model_content=upload_result.result)
|
||||||
return ResponseUtil.success(model_content=upload_result.result)
|
|
||||||
else:
|
|
||||||
logger.warning('上传失败')
|
|
||||||
return ResponseUtil.failure(msg=upload_result.message)
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception(e)
|
|
||||||
return ResponseUtil.error(msg=str(e))
|
|
||||||
|
|
||||||
|
|
||||||
@commonController.get("/download")
|
@commonController.get("/download")
|
||||||
async def common_download(request: Request, background_tasks: BackgroundTasks, file_name: str = Query(alias='fileName'), delete: bool = Query()):
|
async def common_download(request: Request, background_tasks: BackgroundTasks, file_name: str = Query(alias='fileName'), delete: bool = Query()):
|
||||||
try:
|
download_result = await CommonService.download_services(background_tasks, file_name, delete)
|
||||||
download_result = await CommonService.download_services(background_tasks, file_name, delete)
|
logger.info(download_result.message)
|
||||||
if download_result.is_success:
|
|
||||||
logger.info(download_result.message)
|
return ResponseUtil.streaming(data=download_result.result)
|
||||||
return ResponseUtil.streaming(data=download_result.result)
|
|
||||||
else:
|
|
||||||
logger.warning(download_result.message)
|
|
||||||
return ResponseUtil.failure(msg=download_result.message)
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception(e)
|
|
||||||
return ResponseUtil.error(msg=str(e))
|
|
||||||
|
|
||||||
|
|
||||||
@commonController.get("/download/resource")
|
@commonController.get("/download/resource")
|
||||||
async def common_download(request: Request, resource: str = Query()):
|
async def common_download(request: Request, resource: str = Query()):
|
||||||
try:
|
download_resource_result = await CommonService.download_resource_services(resource)
|
||||||
download_resource_result = await CommonService.download_resource_services(resource)
|
logger.info(download_resource_result.message)
|
||||||
if download_resource_result.is_success:
|
|
||||||
logger.info(download_resource_result.message)
|
return ResponseUtil.streaming(data=download_resource_result.result)
|
||||||
return ResponseUtil.streaming(data=download_resource_result.result)
|
|
||||||
else:
|
|
||||||
logger.warning(download_resource_result.message)
|
|
||||||
return ResponseUtil.failure(msg=download_resource_result.message)
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception(e)
|
|
||||||
return ResponseUtil.error(msg=str(e))
|
|
||||||
|
@@ -4,6 +4,7 @@ from fastapi import UploadFile
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from config.env import UploadConfig
|
from config.env import UploadConfig
|
||||||
from module_admin.entity.vo.common_vo import *
|
from module_admin.entity.vo.common_vo import *
|
||||||
|
from exceptions.exception import ServiceException
|
||||||
from utils.upload_util import UploadUtil
|
from utils.upload_util import UploadUtil
|
||||||
|
|
||||||
|
|
||||||
@@ -21,7 +22,7 @@ class CommonService:
|
|||||||
:return: 上传结果
|
:return: 上传结果
|
||||||
"""
|
"""
|
||||||
if not UploadUtil.check_file_extension(file):
|
if not UploadUtil.check_file_extension(file):
|
||||||
result = dict(is_success=False, message='文件类型不合法')
|
raise ServiceException(message='文件类型不合法')
|
||||||
else:
|
else:
|
||||||
relative_path = f'upload/{datetime.now().strftime("%Y")}/{datetime.now().strftime("%m")}/{datetime.now().strftime("%d")}'
|
relative_path = f'upload/{datetime.now().strftime("%Y")}/{datetime.now().strftime("%m")}/{datetime.now().strftime("%d")}'
|
||||||
dir_path = os.path.join(UploadConfig.UPLOAD_PATH, relative_path)
|
dir_path = os.path.join(UploadConfig.UPLOAD_PATH, relative_path)
|
||||||
@@ -36,7 +37,7 @@ class CommonService:
|
|||||||
for chunk in iter(lambda: file.file.read(1024 * 1024 * 10), b''):
|
for chunk in iter(lambda: file.file.read(1024 * 1024 * 10), b''):
|
||||||
f.write(chunk)
|
f.write(chunk)
|
||||||
|
|
||||||
result = dict(
|
return CrudResponseModel(
|
||||||
is_success=True,
|
is_success=True,
|
||||||
result=UploadResponseModel(
|
result=UploadResponseModel(
|
||||||
fileName=f'{UploadConfig.UPLOAD_PREFIX}/{relative_path}/{filename}',
|
fileName=f'{UploadConfig.UPLOAD_PREFIX}/{relative_path}/{filename}',
|
||||||
@@ -47,8 +48,6 @@ class CommonService:
|
|||||||
message='上传成功'
|
message='上传成功'
|
||||||
)
|
)
|
||||||
|
|
||||||
return CrudResponseModel(**result)
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def download_services(cls, background_tasks: BackgroundTasks, file_name, delete: bool):
|
async def download_services(cls, background_tasks: BackgroundTasks, file_name, delete: bool):
|
||||||
"""
|
"""
|
||||||
@@ -60,14 +59,13 @@ class CommonService:
|
|||||||
"""
|
"""
|
||||||
filepath = os.path.join(UploadConfig.DOWNLOAD_PATH, file_name)
|
filepath = os.path.join(UploadConfig.DOWNLOAD_PATH, file_name)
|
||||||
if '..' in file_name:
|
if '..' in file_name:
|
||||||
result = dict(is_success=False, message='文件名称不合法')
|
raise ServiceException(message='文件名称不合法')
|
||||||
elif not UploadUtil.check_file_exists(filepath):
|
elif not UploadUtil.check_file_exists(filepath):
|
||||||
result = dict(is_success=False, message='文件不存在')
|
raise ServiceException(message='文件不存在')
|
||||||
else:
|
else:
|
||||||
result = dict(is_success=True, result=UploadUtil.generate_file(filepath), message='下载成功')
|
|
||||||
if delete:
|
if delete:
|
||||||
background_tasks.add_task(UploadUtil.delete_file, filepath)
|
background_tasks.add_task(UploadUtil.delete_file, filepath)
|
||||||
return CrudResponseModel(**result)
|
return CrudResponseModel(is_success=True, result=UploadUtil.generate_file(filepath), message='下载成功')
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def download_resource_services(cls, resource: str):
|
async def download_resource_services(cls, resource: str):
|
||||||
@@ -79,9 +77,8 @@ class CommonService:
|
|||||||
filepath = os.path.join(resource.replace(UploadConfig.UPLOAD_PREFIX, UploadConfig.UPLOAD_PATH))
|
filepath = os.path.join(resource.replace(UploadConfig.UPLOAD_PREFIX, UploadConfig.UPLOAD_PATH))
|
||||||
filename = resource.rsplit("/", 1)[-1]
|
filename = resource.rsplit("/", 1)[-1]
|
||||||
if '..' in filename or not UploadUtil.check_file_timestamp(filename) or not UploadUtil.check_file_machine(filename) or not UploadUtil.check_file_random_code(filename):
|
if '..' in filename or not UploadUtil.check_file_timestamp(filename) or not UploadUtil.check_file_machine(filename) or not UploadUtil.check_file_random_code(filename):
|
||||||
result = dict(is_success=False, message='文件名称不合法')
|
raise ServiceException(message='文件名称不合法')
|
||||||
elif not UploadUtil.check_file_exists(filepath):
|
elif not UploadUtil.check_file_exists(filepath):
|
||||||
result = dict(is_success=False, message='文件不存在')
|
raise ServiceException(message='文件不存在')
|
||||||
else:
|
else:
|
||||||
result = dict(is_success=True, result=UploadUtil.generate_file(filepath), message='下载成功')
|
return CrudResponseModel(is_success=True, result=UploadUtil.generate_file(filepath), message='下载成功')
|
||||||
return CrudResponseModel(**result)
|
|
||||||
|
Reference in New Issue
Block a user