6 changed files with 246 additions and 78 deletions
@ -1,87 +1,53 @@ |
|||||
from fastapi import APIRouter, Request |
from fastapi import APIRouter |
||||
from fastapi import Depends, File, Form, Query |
from fastapi import Depends, File, Query |
||||
from sqlalchemy.orm import Session |
|
||||
from config.env import CachePathConfig |
|
||||
from config.get_db import get_db |
|
||||
from module_admin.service.login_service import LoginService |
from module_admin.service.login_service import LoginService |
||||
from module_admin.service.common_service import * |
from module_admin.service.common_service import * |
||||
from module_admin.service.config_service import ConfigService |
|
||||
from utils.response_util import * |
from utils.response_util import * |
||||
from utils.log_util import * |
from utils.log_util import * |
||||
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth |
|
||||
from typing import Optional |
|
||||
|
|
||||
|
commonController = APIRouter(prefix='/common', dependencies=[Depends(LoginService.get_current_user)]) |
||||
|
|
||||
commonController = APIRouter(prefix='/common') |
|
||||
|
|
||||
|
@commonController.post("/upload") |
||||
@commonController.post("/upload", dependencies=[Depends(LoginService.get_current_user), Depends(CheckUserInterfaceAuth('common'))]) |
async def common_upload(request: Request, file: UploadFile = File(...)): |
||||
async def common_upload(request: Request, taskPath: str = Form(), uploadId: str = Form(), file: UploadFile = File(...)): |
|
||||
try: |
|
||||
try: |
|
||||
os.makedirs(os.path.join(CachePathConfig.PATH, taskPath, uploadId)) |
|
||||
except FileExistsError: |
|
||||
pass |
|
||||
CommonService.upload_service(CachePathConfig.PATH, taskPath, uploadId, file) |
|
||||
logger.info('上传成功') |
|
||||
return response_200(data={'filename': file.filename, 'path': f'/common/{CachePathConfig.PATHSTR}?taskPath={taskPath}&taskId={uploadId}&filename={file.filename}'}, message="上传成功") |
|
||||
except Exception as e: |
|
||||
logger.exception(e) |
|
||||
return response_500(data="", message=str(e)) |
|
||||
|
|
||||
|
|
||||
@commonController.post("/uploadForEditor", dependencies=[Depends(LoginService.get_current_user), Depends(CheckUserInterfaceAuth('common'))]) |
|
||||
async def editor_upload(request: Request, baseUrl: str = Form(), uploadId: str = Form(), taskPath: str = Form(), file: UploadFile = File(...)): |
|
||||
try: |
try: |
||||
try: |
upload_result = CommonService.upload_service(request, file) |
||||
os.makedirs(os.path.join(CachePathConfig.PATH, taskPath, uploadId)) |
if upload_result.is_success: |
||||
except FileExistsError: |
logger.info('上传成功') |
||||
pass |
return ResponseUtil.success(model_content=upload_result.result) |
||||
CommonService.upload_service(CachePathConfig.PATH, taskPath, uploadId, file) |
else: |
||||
logger.info('上传成功') |
logger.warning('上传失败') |
||||
return JSONResponse( |
return ResponseUtil.failure(msg=upload_result.message) |
||||
status_code=status.HTTP_200_OK, |
|
||||
content=jsonable_encoder( |
|
||||
{ |
|
||||
'errno': 0, |
|
||||
'data': { |
|
||||
'url': f'{baseUrl}/common/{CachePathConfig.PATHSTR}?taskPath={taskPath}&taskId={uploadId}&filename={file.filename}' |
|
||||
}, |
|
||||
} |
|
||||
) |
|
||||
) |
|
||||
except Exception as e: |
except Exception as e: |
||||
logger.exception(e) |
logger.exception(e) |
||||
return JSONResponse( |
return ResponseUtil.error(msg=str(e)) |
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
|
||||
content=jsonable_encoder( |
|
||||
{ |
|
||||
'errno': 1, |
|
||||
'message': str(e), |
|
||||
} |
|
||||
) |
|
||||
) |
|
||||
|
|
||||
|
|
||||
@commonController.get(f"/{CachePathConfig.PATHSTR}") |
@commonController.get("/download") |
||||
async def common_download(request: Request, task_path: str = Query(alias='taskPath'), task_id: str = Query(alias='taskId'), filename: str = Query()): |
async def common_download(request: Request, background_tasks: BackgroundTasks, file_name: str = Query(alias='fileName'), delete: bool = Query()): |
||||
try: |
try: |
||||
def generate_file(): |
download_result = CommonService.download_services(background_tasks, file_name, delete) |
||||
with open(os.path.join(CachePathConfig.PATH, task_path, task_id, filename), 'rb') as response_file: |
if download_result.is_success: |
||||
yield from response_file |
logger.info(download_result.message) |
||||
return streaming_response_200(data=generate_file()) |
return ResponseUtil.streaming(data=download_result.result) |
||||
|
else: |
||||
|
logger.warning(download_result.message) |
||||
|
return ResponseUtil.failure(msg=download_result.message) |
||||
except Exception as e: |
except Exception as e: |
||||
logger.exception(e) |
logger.exception(e) |
||||
return response_500(data="", message=str(e)) |
return ResponseUtil.error(msg=str(e)) |
||||
|
|
||||
|
|
||||
@commonController.get("/config/query/{config_key}") |
@commonController.get("/download/resource") |
||||
async def query_system_config(request: Request, config_key: str): |
async def common_download(request: Request, resource: str = Query()): |
||||
try: |
try: |
||||
# 获取全量数据 |
download_resource_result = CommonService.download_resource_services(resource) |
||||
config_query_result = await ConfigService.query_config_list_from_cache_services(request.app.state.redis, config_key) |
if download_resource_result.is_success: |
||||
logger.info('获取成功') |
logger.info(download_resource_result.message) |
||||
return response_200(data=config_query_result, message="获取成功") |
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: |
except Exception as e: |
||||
logger.exception(e) |
logger.exception(e) |
||||
return response_500(data="", message=str(e)) |
return ResponseUtil.error(msg=str(e)) |
||||
|
@ -0,0 +1,83 @@ |
|||||
|
import random |
||||
|
import os |
||||
|
from fastapi import UploadFile |
||||
|
from datetime import datetime |
||||
|
from config.env import UploadConfig |
||||
|
|
||||
|
|
||||
|
class UploadUtil: |
||||
|
""" |
||||
|
上传工具类 |
||||
|
""" |
||||
|
|
||||
|
@classmethod |
||||
|
def generate_random_number(cls): |
||||
|
""" |
||||
|
生成3位数字构成的字符串 |
||||
|
""" |
||||
|
random_number = random.randint(1, 999) |
||||
|
|
||||
|
return f'{random_number:03}' |
||||
|
|
||||
|
@classmethod |
||||
|
def check_file_exists(cls, filepath): |
||||
|
""" |
||||
|
检查文件是否存在 |
||||
|
""" |
||||
|
return os.path.exists(filepath) |
||||
|
|
||||
|
@classmethod |
||||
|
def check_file_extension(cls, file: UploadFile): |
||||
|
""" |
||||
|
检查文件后缀是否合法 |
||||
|
""" |
||||
|
file_extension = file.filename.rsplit('.', 1)[-1] |
||||
|
if file_extension in UploadConfig.DEFAULT_ALLOWED_EXTENSION: |
||||
|
return True |
||||
|
return False |
||||
|
|
||||
|
@classmethod |
||||
|
def check_file_timestamp(cls, filename): |
||||
|
""" |
||||
|
校验文件时间戳是否合法 |
||||
|
""" |
||||
|
timestamp = filename.rsplit('.', 1)[0].split('_')[-1].split(UploadConfig.UPLOAD_MACHINE)[0] |
||||
|
try: |
||||
|
datetime.strptime(timestamp, '%Y%m%d%H%M%S') |
||||
|
return True |
||||
|
except ValueError: |
||||
|
return False |
||||
|
|
||||
|
@classmethod |
||||
|
def check_file_machine(cls, filename): |
||||
|
""" |
||||
|
校验文件机器码是否合法 |
||||
|
""" |
||||
|
if filename.rsplit('.', 1)[0][-4] == UploadConfig.UPLOAD_MACHINE: |
||||
|
return True |
||||
|
return False |
||||
|
|
||||
|
@classmethod |
||||
|
def check_file_random_code(cls, filename): |
||||
|
""" |
||||
|
校验文件随机码是否合法 |
||||
|
""" |
||||
|
valid_code_list = [f"{i:03}" for i in range(1, 999)] |
||||
|
if filename.rsplit('.', 1)[0][-3:] in valid_code_list: |
||||
|
return True |
||||
|
return False |
||||
|
|
||||
|
@classmethod |
||||
|
def generate_file(cls, filepath): |
||||
|
""" |
||||
|
根据文件生成二进制数据 |
||||
|
""" |
||||
|
with open(filepath, 'rb') as response_file: |
||||
|
yield from response_file |
||||
|
|
||||
|
@classmethod |
||||
|
def delete_file(cls, filepath: str): |
||||
|
""" |
||||
|
根据文件路径删除对应文件 |
||||
|
""" |
||||
|
os.remove(filepath) |
Loading…
Reference in new issue