diff --git a/backend/README.md b/backend/README.md index 7b61a75f..29f381cf 100644 --- a/backend/README.md +++ b/backend/README.md @@ -1,6 +1,6 @@ # FastApiAdmin - Backend -一个基于 FastAPI 的现代化后端管理系统,为前端 Vue3 管理系统提供完整的 API 服务支持。 +一个基于 FastAPI 框架构建企业级后端架构解决方案,为前端 Vue3 管理系统提供完整的 API 服务支持。 ## 🚀 项目特性 diff --git a/backend/app/api/v1/module_application/ai/controller.py b/backend/app/api/v1/module_application/ai/controller.py index dc523846..3a62c74c 100644 --- a/backend/app/api/v1/module_application/ai/controller.py +++ b/backend/app/api/v1/module_application/ai/controller.py @@ -9,6 +9,7 @@ from app.core.base_params import PaginationQueryParam from app.core.dependencies import AuthPermission from app.core.router_class import OperationLogRoute from app.core.logger import logger + from app.api.v1.module_system.auth.schema import AuthSchema from .param import McpQueryParam from .service import McpService diff --git a/backend/app/api/v1/module_application/ai/crud.py b/backend/app/api/v1/module_application/ai/crud.py index d6f9f6eb..9e456139 100644 --- a/backend/app/api/v1/module_application/ai/crud.py +++ b/backend/app/api/v1/module_application/ai/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from app.api.v1.module_system.auth.schema import AuthSchema from .model import McpModel from .schema import McpCreateSchema, McpUpdateSchema diff --git a/backend/app/api/v1/module_application/ai/service.py b/backend/app/api/v1/module_application/ai/service.py index c5b87137..99575330 100644 --- a/backend/app/api/v1/module_application/ai/service.py +++ b/backend/app/api/v1/module_application/ai/service.py @@ -3,8 +3,9 @@ from typing import List, Dict, Optional, Any from app.core.exceptions import CustomException -from app.api.v1.module_system.auth.schema import AuthSchema from app.utils.ai_util import AIClient + +from app.api.v1.module_system.auth.schema import AuthSchema from .schema import McpCreateSchema, McpUpdateSchema, McpOutSchema, ChatQuerySchema from .param import McpQueryParam from .crud import McpCRUD diff --git a/backend/app/api/v1/module_application/job/controller.py b/backend/app/api/v1/module_application/job/controller.py index cbe10dd9..e22d0ecd 100644 --- a/backend/app/api/v1/module_application/job/controller.py +++ b/backend/app/api/v1/module_application/job/controller.py @@ -10,6 +10,7 @@ from app.core.base_params import PaginationQueryParam from app.core.dependencies import AuthPermission from app.core.router_class import OperationLogRoute from app.core.logger import logger + from app.api.v1.module_system.auth.schema import AuthSchema from .param import JobQueryParam, JobLogQueryParam from .service import JobService, JobLogService diff --git a/backend/app/api/v1/module_application/job/crud.py b/backend/app/api/v1/module_application/job/crud.py index 9fab74c7..ce288053 100644 --- a/backend/app/api/v1/module_application/job/crud.py +++ b/backend/app/api/v1/module_application/job/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from app.api.v1.module_system.auth.schema import AuthSchema from .model import JobModel, JobLogModel from .schema import JobCreateSchema,JobUpdateSchema,JobLogCreateSchema,JobLogUpdateSchema diff --git a/backend/app/api/v1/module_application/job/service.py b/backend/app/api/v1/module_application/job/service.py index 93bc797c..c6f7f87e 100644 --- a/backend/app/api/v1/module_application/job/service.py +++ b/backend/app/api/v1/module_application/job/service.py @@ -6,6 +6,7 @@ from app.core.ap_scheduler import SchedulerUtil from app.core.exceptions import CustomException from app.utils.cron_util import CronUtil from app.utils.excel_util import ExcelUtil + from app.api.v1.module_system.auth.schema import AuthSchema from .schema import JobCreateSchema, JobUpdateSchema, JobOutSchema, JobLogOutSchema from .param import JobQueryParam, JobLogQueryParam diff --git a/backend/app/api/v1/module_application/myapp/controller.py b/backend/app/api/v1/module_application/myapp/controller.py index 6067ba5a..6446d096 100644 --- a/backend/app/api/v1/module_application/myapp/controller.py +++ b/backend/app/api/v1/module_application/myapp/controller.py @@ -10,6 +10,7 @@ from app.core.dependencies import AuthPermission from app.core.router_class import OperationLogRoute from app.core.base_schema import BatchSetAvailable from app.core.logger import logger + from app.api.v1.module_system.auth.schema import AuthSchema from .param import ApplicationQueryParam from .service import ApplicationService diff --git a/backend/app/api/v1/module_application/myapp/crud.py b/backend/app/api/v1/module_application/myapp/crud.py index 3a97e214..32955ad9 100644 --- a/backend/app/api/v1/module_application/myapp/crud.py +++ b/backend/app/api/v1/module_application/myapp/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from app.api.v1.module_system.auth.schema import AuthSchema from .model import ApplicationModel from .schema import ApplicationCreateSchema, ApplicationUpdateSchema diff --git a/backend/app/api/v1/module_application/myapp/schema.py b/backend/app/api/v1/module_application/myapp/schema.py index 817d11e2..b82e58d2 100644 --- a/backend/app/api/v1/module_application/myapp/schema.py +++ b/backend/app/api/v1/module_application/myapp/schema.py @@ -2,9 +2,9 @@ from typing import Optional from pydantic import BaseModel, ConfigDict, Field, field_validator +from urllib.parse import urlparse from app.core.base_schema import BaseSchema -from urllib.parse import urlparse class ApplicationCreateSchema(BaseModel): diff --git a/backend/app/api/v1/module_application/myapp/service.py b/backend/app/api/v1/module_application/myapp/service.py index 6f5a96be..3e95f448 100644 --- a/backend/app/api/v1/module_application/myapp/service.py +++ b/backend/app/api/v1/module_application/myapp/service.py @@ -4,7 +4,7 @@ from typing import List, Dict, Optional from app.core.base_schema import BatchSetAvailable from app.core.exceptions import CustomException -from app.core.logger import logger + from app.api.v1.module_system.auth.schema import AuthSchema from .schema import ApplicationCreateSchema, ApplicationUpdateSchema, ApplicationOutSchema from .param import ApplicationQueryParam diff --git a/backend/app/api/v1/module_common/file/controller.py b/backend/app/api/v1/module_common/file/controller.py index 6bf307e0..47b73519 100644 --- a/backend/app/api/v1/module_common/file/controller.py +++ b/backend/app/api/v1/module_common/file/controller.py @@ -9,8 +9,10 @@ from app.core.router_class import OperationLogRoute from app.core.logger import logger from app.common.response import SuccessResponse, UploadFileResponse from app.utils.upload_util import UploadUtil + from .service import FileService + FileRouter = APIRouter(route_class=OperationLogRoute, prefix="/file", tags=["文件管理"]) @FileRouter.post("/upload", summary="上传文件", description="上传文件",dependencies=[Depends(AuthPermission(["module_common:file:upload"]))]) diff --git a/backend/app/api/v1/module_common/file/schema.py b/backend/app/api/v1/module_common/file/schema.py index 5d1add78..5d7c6f25 100644 --- a/backend/app/api/v1/module_common/file/schema.py +++ b/backend/app/api/v1/module_common/file/schema.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- + from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from pydantic.alias_generators import to_camel from typing import Optional diff --git a/backend/app/api/v1/module_common/file/service.py b/backend/app/api/v1/module_common/file/service.py index 30c8ad94..616734ac 100644 --- a/backend/app/api/v1/module_common/file/service.py +++ b/backend/app/api/v1/module_common/file/service.py @@ -8,6 +8,7 @@ from app.core.exceptions import CustomException from app.core.base_schema import UploadResponseSchema, DownloadFileSchema from app.utils.upload_util import UploadUtil + class FileService: """ 文件管理服务层 diff --git a/backend/app/api/v1/module_generator/demo/controller.py b/backend/app/api/v1/module_generator/demo/controller.py index 60dcb20d..5bbb8de1 100644 --- a/backend/app/api/v1/module_generator/demo/controller.py +++ b/backend/app/api/v1/module_generator/demo/controller.py @@ -11,6 +11,8 @@ from app.core.dependencies import AuthPermission from app.core.router_class import OperationLogRoute from app.core.base_schema import BatchSetAvailable from app.core.logger import logger + + from app.api.v1.module_system.auth.schema import AuthSchema from .param import DemoQueryParam from .service import DemoService diff --git a/backend/app/api/v1/module_generator/demo/crud.py b/backend/app/api/v1/module_generator/demo/crud.py index c4c08b92..b1778883 100644 --- a/backend/app/api/v1/module_generator/demo/crud.py +++ b/backend/app/api/v1/module_generator/demo/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from app.api.v1.module_system.auth.schema import AuthSchema from .model import DemoModel from .schema import DemoCreateSchema, DemoUpdateSchema, DemoOutSchema diff --git a/backend/app/api/v1/module_generator/demo/param.py b/backend/app/api/v1/module_generator/demo/param.py index ac73a20f..8e241446 100644 --- a/backend/app/api/v1/module_generator/demo/param.py +++ b/backend/app/api/v1/module_generator/demo/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class DemoQueryParam: """示例查询参数""" diff --git a/backend/app/api/v1/module_generator/demo/service.py b/backend/app/api/v1/module_generator/demo/service.py index 6a0b912f..45935648 100644 --- a/backend/app/api/v1/module_generator/demo/service.py +++ b/backend/app/api/v1/module_generator/demo/service.py @@ -9,6 +9,7 @@ from app.core.base_schema import BatchSetAvailable from app.core.exceptions import CustomException from app.utils.excel_util import ExcelUtil from app.core.logger import logger + from app.api.v1.module_system.auth.schema import AuthSchema from .schema import DemoCreateSchema, DemoUpdateSchema, DemoOutSchema from .param import DemoQueryParam diff --git a/backend/app/api/v1/module_generator/gencode/controller.py b/backend/app/api/v1/module_generator/gencode/controller.py index 2ad7cc24..0e084010 100644 --- a/backend/app/api/v1/module_generator/gencode/controller.py +++ b/backend/app/api/v1/module_generator/gencode/controller.py @@ -9,9 +9,10 @@ from app.core.dependencies import AuthPermission from app.core.router_class import OperationLogRoute from app.core.base_params import PaginationQueryParam from app.common.request import PaginationService -from app.api.v1.module_system.auth.schema import AuthSchema from app.utils.common_util import bytes2file_response from app.core.logger import logger + +from app.api.v1.module_system.auth.schema import AuthSchema from .param import GenTableQueryParam from .schema import GenTableSchema from .service import GenTableService diff --git a/backend/app/api/v1/module_generator/gencode/crud.py b/backend/app/api/v1/module_generator/gencode/crud.py index 8dae3605..5900a97c 100644 --- a/backend/app/api/v1/module_generator/gencode/crud.py +++ b/backend/app/api/v1/module_generator/gencode/crud.py @@ -8,6 +8,7 @@ from sqlglot.expressions import Expression from app.core.logger import logger from app.config.setting import settings from app.core.base_crud import CRUDBase + from app.api.v1.module_system.auth.schema import AuthSchema from .param import GenTableQueryParam from .model import GenTableModel, GenTableColumnModel diff --git a/backend/app/api/v1/module_generator/gencode/service.py b/backend/app/api/v1/module_generator/gencode/service.py index 0784f75a..1348bb5d 100644 --- a/backend/app/api/v1/module_generator/gencode/service.py +++ b/backend/app/api/v1/module_generator/gencode/service.py @@ -1,7 +1,6 @@ # -*- coding:utf-8 -*- import io -import json import os import zipfile from typing import Any, List, Dict, Literal, Optional @@ -11,9 +10,10 @@ from sqlglot import parse as sqlglot_parse from app.config.setting import settings from app.core.logger import logger from app.core.exceptions import CustomException -from app.api.v1.module_system.auth.schema import AuthSchema from app.utils.gen_util import GenUtils from app.utils.jinja2_template_util import Jinja2TemplateUtil + +from app.api.v1.module_system.auth.schema import AuthSchema from .schema import GenTableSchema, GenTableOutSchema, GenTableColumnSchema, GenTableColumnOutSchema from .param import GenTableQueryParam from .crud import GenTableColumnCRUD, GenTableCRUD diff --git a/backend/app/api/v1/module_monitor/cache/controller.py b/backend/app/api/v1/module_monitor/cache/controller.py index ac417e4e..8373d72a 100644 --- a/backend/app/api/v1/module_monitor/cache/controller.py +++ b/backend/app/api/v1/module_monitor/cache/controller.py @@ -9,6 +9,7 @@ from app.core.exceptions import CustomException from app.core.router_class import OperationLogRoute from app.core.dependencies import AuthPermission, redis_getter from app.core.logger import logger + from .service import CacheService diff --git a/backend/app/api/v1/module_monitor/cache/service.py b/backend/app/api/v1/module_monitor/cache/service.py index eeaa5351..8b288139 100644 --- a/backend/app/api/v1/module_monitor/cache/service.py +++ b/backend/app/api/v1/module_monitor/cache/service.py @@ -4,6 +4,7 @@ from redis.asyncio.client import Redis from app.common.enums import RedisInitKeyConfig from app.core.redis_crud import RedisCURD + from .schema import CacheMonitorSchema, CacheInfoSchema diff --git a/backend/app/api/v1/module_monitor/online/controller.py b/backend/app/api/v1/module_monitor/online/controller.py index cd9b7a92..40c626d7 100644 --- a/backend/app/api/v1/module_monitor/online/controller.py +++ b/backend/app/api/v1/module_monitor/online/controller.py @@ -10,6 +10,7 @@ from app.core.dependencies import AuthPermission, redis_getter from app.core.base_params import PaginationQueryParam from app.core.router_class import OperationLogRoute from app.core.logger import logger + from .param import OnlineQueryParam from .service import OnlineService diff --git a/backend/app/api/v1/module_monitor/resource/controller.py b/backend/app/api/v1/module_monitor/resource/controller.py index 9833a728..a2d9ea6b 100644 --- a/backend/app/api/v1/module_monitor/resource/controller.py +++ b/backend/app/api/v1/module_monitor/resource/controller.py @@ -11,14 +11,16 @@ from app.core.base_params import PaginationQueryParam from app.core.dependencies import AuthPermission from app.core.router_class import OperationLogRoute from app.core.logger import logger + from .param import ResourceSearchQueryParam +from .service import ResourceService from .schema import ( ResourceMoveSchema, ResourceCopySchema, ResourceRenameSchema, ResourceCreateDirSchema ) -from .service import ResourceService + ResourceRouter = APIRouter(route_class=OperationLogRoute, prefix="/resource", tags=["资源管理"]) diff --git a/backend/app/api/v1/module_monitor/resource/param.py b/backend/app/api/v1/module_monitor/resource/param.py index 84fbd8e0..a77b9ded 100644 --- a/backend/app/api/v1/module_monitor/resource/param.py +++ b/backend/app/api/v1/module_monitor/resource/param.py @@ -3,6 +3,7 @@ from typing import Optional from fastapi import Query + class ResourceSearchQueryParam: """资源搜索查询参数""" diff --git a/backend/app/api/v1/module_monitor/resource/schema.py b/backend/app/api/v1/module_monitor/resource/schema.py index 63b5ec71..fb7c22ea 100644 --- a/backend/app/api/v1/module_monitor/resource/schema.py +++ b/backend/app/api/v1/module_monitor/resource/schema.py @@ -1,9 +1,8 @@ # -*- coding: utf-8 -*- -from typing import Optional, List, Dict, Any +from typing import Optional, List from datetime import datetime from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator -from pathlib import Path from urllib.parse import urlparse diff --git a/backend/app/api/v1/module_monitor/resource/service.py b/backend/app/api/v1/module_monitor/resource/service.py index 441696fb..50ffb8b2 100644 --- a/backend/app/api/v1/module_monitor/resource/service.py +++ b/backend/app/api/v1/module_monitor/resource/service.py @@ -12,6 +12,7 @@ from app.core.exceptions import CustomException from app.core.logger import logger from app.utils.excel_util import ExcelUtil from app.config.setting import settings + from .param import ResourceSearchQueryParam from .schema import ( ResourceItemSchema, diff --git a/backend/app/api/v1/module_monitor/server/controller.py b/backend/app/api/v1/module_monitor/server/controller.py index 42dd587c..d953d07e 100644 --- a/backend/app/api/v1/module_monitor/server/controller.py +++ b/backend/app/api/v1/module_monitor/server/controller.py @@ -8,6 +8,7 @@ from app.common.response import SuccessResponse from app.core.dependencies import AuthPermission from app.core.router_class import OperationLogRoute from app.core.logger import logger + from .service import ServerService diff --git a/backend/app/api/v1/module_monitor/server/service.py b/backend/app/api/v1/module_monitor/server/service.py index 244b70e4..b30f298a 100644 --- a/backend/app/api/v1/module_monitor/server/service.py +++ b/backend/app/api/v1/module_monitor/server/service.py @@ -8,6 +8,7 @@ from pathlib import Path from typing import List, Dict from app.utils.common_util import bytes2human + from .schema import ( CpuInfoSchema, MemoryInfoSchema, diff --git a/backend/app/api/v1/module_system/auth/controller.py b/backend/app/api/v1/module_system/auth/controller.py index e0c9d614..95ffaf59 100644 --- a/backend/app/api/v1/module_system/auth/controller.py +++ b/backend/app/api/v1/module_system/auth/controller.py @@ -17,6 +17,7 @@ from app.core.dependencies import ( get_current_user, redis_getter ) + from .service import ( LoginService, CaptchaService diff --git a/backend/app/api/v1/module_system/auth/service.py b/backend/app/api/v1/module_system/auth/service.py index d9358e4b..112fad82 100644 --- a/backend/app/api/v1/module_system/auth/service.py +++ b/backend/app/api/v1/module_system/auth/service.py @@ -14,15 +14,16 @@ from app.utils.common_util import get_random_character from app.utils.captcha_util import CaptchaUtil from app.utils.ip_local_util import IpLocalUtil from app.utils.hash_bcrpy_util import PwdUtil +from app.core.redis_crud import RedisCURD +from app.core.exceptions import CustomException +from app.core.logger import logger +from app.config.setting import settings from app.core.security import ( CustomOAuth2PasswordRequestForm, create_access_token, decode_access_token ) -from app.core.redis_crud import RedisCURD -from app.core.exceptions import CustomException -from app.core.logger import logger -from app.config.setting import settings + from app.api.v1.module_monitor.online.schema import OnlineOutSchema from ..user.crud import UserCRUD from ..user.model import UserModel diff --git a/backend/app/api/v1/module_system/dept/controller.py b/backend/app/api/v1/module_system/dept/controller.py index 79d152cb..e94cf5d8 100644 --- a/backend/app/api/v1/module_system/dept/controller.py +++ b/backend/app/api/v1/module_system/dept/controller.py @@ -8,6 +8,7 @@ from app.core.router_class import OperationLogRoute from app.core.dependencies import AuthPermission from app.core.base_schema import BatchSetAvailable from app.core.logger import logger + from ..auth.schema import AuthSchema from .param import DeptQueryParam from .service import DeptService diff --git a/backend/app/api/v1/module_system/dept/crud.py b/backend/app/api/v1/module_system/dept/crud.py index 84c70191..8fbac1a4 100644 --- a/backend/app/api/v1/module_system/dept/crud.py +++ b/backend/app/api/v1/module_system/dept/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from ..auth.schema import AuthSchema from .model import DeptModel from .schema import DeptCreateSchema, DeptUpdateSchema diff --git a/backend/app/api/v1/module_system/dept/param.py b/backend/app/api/v1/module_system/dept/param.py index bf0715ee..8518a80e 100644 --- a/backend/app/api/v1/module_system/dept/param.py +++ b/backend/app/api/v1/module_system/dept/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class DeptQueryParam: """部门管理查询参数""" diff --git a/backend/app/api/v1/module_system/dept/service.py b/backend/app/api/v1/module_system/dept/service.py index 19b67b34..43b2b613 100644 --- a/backend/app/api/v1/module_system/dept/service.py +++ b/backend/app/api/v1/module_system/dept/service.py @@ -11,6 +11,7 @@ from app.utils.common_util import ( get_child_recursion, traversal_to_tree ) + from ..auth.schema import AuthSchema from .crud import DeptCRUD from .param import DeptQueryParam diff --git a/backend/app/api/v1/module_system/dict/controller.py b/backend/app/api/v1/module_system/dict/controller.py index 4e05775e..568b11a5 100644 --- a/backend/app/api/v1/module_system/dict/controller.py +++ b/backend/app/api/v1/module_system/dict/controller.py @@ -13,6 +13,7 @@ from app.core.router_class import OperationLogRoute from app.core.logger import logger from app.common.request import PaginationService from app.utils.common_util import bytes2file_response + from ..auth.schema import AuthSchema from .param import DictTypeQueryParam, DictDataQueryParam from .service import DictTypeService, DictDataService diff --git a/backend/app/api/v1/module_system/dict/crud.py b/backend/app/api/v1/module_system/dict/crud.py index b2d4e31b..9c61e315 100644 --- a/backend/app/api/v1/module_system/dict/crud.py +++ b/backend/app/api/v1/module_system/dict/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from app.api.v1.module_system.dict.model import DictDataModel, DictTypeModel from app.api.v1.module_system.dict.schema import DictDataCreateSchema, DictDataUpdateSchema, DictTypeCreateSchema, DictTypeUpdateSchema from app.api.v1.module_system.auth.schema import AuthSchema diff --git a/backend/app/api/v1/module_system/dict/service.py b/backend/app/api/v1/module_system/dict/service.py index efa48258..5f90562a 100644 --- a/backend/app/api/v1/module_system/dict/service.py +++ b/backend/app/api/v1/module_system/dict/service.py @@ -6,11 +6,12 @@ from redis.asyncio.client import Redis from app.common.enums import RedisInitKeyConfig from app.utils.excel_util import ExcelUtil -from app.core.database import AsyncSessionLocal +from app.core.database import async_db_session from app.core.base_schema import BatchSetAvailable from app.core.redis_crud import RedisCURD from app.core.exceptions import CustomException from app.core.logger import logger + from app.api.v1.module_system.auth.schema import AuthSchema from .schema import DictDataCreateSchema,DictDataOutSchema,DictDataUpdateSchema,DictTypeCreateSchema,DictTypeOutSchema,DictTypeUpdateSchema from .param import DictDataQueryParam, DictTypeQueryParam @@ -280,7 +281,7 @@ class DictDataService: 返回: - None """ - async with AsyncSessionLocal() as session: + async with async_db_session() as session: async with session.begin(): auth = AuthSchema(db=session) obj_list = await DictTypeCRUD(auth).get_obj_list_crud() diff --git a/backend/app/api/v1/module_system/log/controller.py b/backend/app/api/v1/module_system/log/controller.py index a0923c46..8b8ab5aa 100644 --- a/backend/app/api/v1/module_system/log/controller.py +++ b/backend/app/api/v1/module_system/log/controller.py @@ -10,6 +10,7 @@ from app.core.router_class import OperationLogRoute from app.core.dependencies import AuthPermission from app.core.base_params import PaginationQueryParam from app.core.logger import logger + from ..auth.schema import AuthSchema from .param import OperationLogQueryParam from .service import OperationLogService diff --git a/backend/app/api/v1/module_system/log/crud.py b/backend/app/api/v1/module_system/log/crud.py index f442dba3..fa5cec3f 100644 --- a/backend/app/api/v1/module_system/log/crud.py +++ b/backend/app/api/v1/module_system/log/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from ..auth.schema import AuthSchema from .model import OperationLogModel from .schema import OperationLogCreateSchema diff --git a/backend/app/api/v1/module_system/log/param.py b/backend/app/api/v1/module_system/log/param.py index db0dd60e..af2e3833 100644 --- a/backend/app/api/v1/module_system/log/param.py +++ b/backend/app/api/v1/module_system/log/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class OperationLogQueryParam: """操作日志查询参数""" diff --git a/backend/app/api/v1/module_system/log/schema.py b/backend/app/api/v1/module_system/log/schema.py index 8c2bba2d..9e934893 100644 --- a/backend/app/api/v1/module_system/log/schema.py +++ b/backend/app/api/v1/module_system/log/schema.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- +import re from typing import Optional from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from app.core.base_schema import BaseSchema -import re class OperationLogCreateSchema(BaseModel): diff --git a/backend/app/api/v1/module_system/log/service.py b/backend/app/api/v1/module_system/log/service.py index deb2e52a..1139da0c 100644 --- a/backend/app/api/v1/module_system/log/service.py +++ b/backend/app/api/v1/module_system/log/service.py @@ -4,6 +4,7 @@ from typing import Any, Dict, List, Optional from app.core.exceptions import CustomException from app.utils.excel_util import ExcelUtil + from ..auth.schema import AuthSchema from .param import OperationLogQueryParam from .crud import OperationLogCRUD diff --git a/backend/app/api/v1/module_system/menu/controller.py b/backend/app/api/v1/module_system/menu/controller.py index 92668143..45daf6ca 100644 --- a/backend/app/api/v1/module_system/menu/controller.py +++ b/backend/app/api/v1/module_system/menu/controller.py @@ -8,6 +8,7 @@ from app.core.dependencies import AuthPermission from app.core.base_schema import BatchSetAvailable from app.core.router_class import OperationLogRoute from app.core.logger import logger + from ..auth.schema import AuthSchema from .param import MenuQueryParam from .service import MenuService diff --git a/backend/app/api/v1/module_system/menu/crud.py b/backend/app/api/v1/module_system/menu/crud.py index d7bd1489..760297cc 100644 --- a/backend/app/api/v1/module_system/menu/crud.py +++ b/backend/app/api/v1/module_system/menu/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from ..auth.schema import AuthSchema from .model import MenuModel from .schema import MenuCreateSchema, MenuUpdateSchema diff --git a/backend/app/api/v1/module_system/menu/model.py b/backend/app/api/v1/module_system/menu/model.py index d36dfb0a..c40dca5d 100644 --- a/backend/app/api/v1/module_system/menu/model.py +++ b/backend/app/api/v1/module_system/menu/model.py @@ -5,7 +5,6 @@ """ from typing import Optional, List, TYPE_CHECKING - from sqlalchemy import Boolean, String, Integer, JSON, ForeignKey from sqlalchemy.orm import relationship, Mapped, mapped_column diff --git a/backend/app/api/v1/module_system/menu/param.py b/backend/app/api/v1/module_system/menu/param.py index 7e6259c4..f4961887 100644 --- a/backend/app/api/v1/module_system/menu/param.py +++ b/backend/app/api/v1/module_system/menu/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class MenuQueryParam: """菜单管理查询参数""" diff --git a/backend/app/api/v1/module_system/menu/service.py b/backend/app/api/v1/module_system/menu/service.py index e33bdde7..fa01a339 100644 --- a/backend/app/api/v1/module_system/menu/service.py +++ b/backend/app/api/v1/module_system/menu/service.py @@ -11,6 +11,7 @@ from app.utils.common_util import ( get_child_recursion, traversal_to_tree ) + from ..auth.schema import AuthSchema from .param import MenuQueryParam from .crud import MenuCRUD diff --git a/backend/app/api/v1/module_system/notice/controller.py b/backend/app/api/v1/module_system/notice/controller.py index 1e9499f0..1e995d40 100644 --- a/backend/app/api/v1/module_system/notice/controller.py +++ b/backend/app/api/v1/module_system/notice/controller.py @@ -11,6 +11,7 @@ from app.core.base_schema import BatchSetAvailable from app.core.logger import logger from app.common.request import PaginationService from app.utils.common_util import bytes2file_response + from ..auth.schema import AuthSchema from .param import NoticeQueryParam from .service import NoticeService diff --git a/backend/app/api/v1/module_system/notice/crud.py b/backend/app/api/v1/module_system/notice/crud.py index 5db44a80..ac47b7cd 100644 --- a/backend/app/api/v1/module_system/notice/crud.py +++ b/backend/app/api/v1/module_system/notice/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from ..auth.schema import AuthSchema from .model import NoticeModel from .schema import NoticeCreateSchema, NoticeUpdateSchema diff --git a/backend/app/api/v1/module_system/notice/model.py b/backend/app/api/v1/module_system/notice/model.py index a99bf6b8..6a066a75 100644 --- a/backend/app/api/v1/module_system/notice/model.py +++ b/backend/app/api/v1/module_system/notice/model.py @@ -5,7 +5,6 @@ """ from typing import Optional - from sqlalchemy import Boolean, String, Text from sqlalchemy.orm import Mapped, mapped_column diff --git a/backend/app/api/v1/module_system/notice/service.py b/backend/app/api/v1/module_system/notice/service.py index b69b81d0..feca3a70 100644 --- a/backend/app/api/v1/module_system/notice/service.py +++ b/backend/app/api/v1/module_system/notice/service.py @@ -6,6 +6,7 @@ from typing import Any, List, Dict, Optional from app.core.base_schema import BatchSetAvailable from app.core.exceptions import CustomException from app.utils.excel_util import ExcelUtil + from ..auth.schema import AuthSchema from .schema import NoticeCreateSchema, NoticeUpdateSchema, NoticeOutSchema from .param import NoticeQueryParam diff --git a/backend/app/api/v1/module_system/params/controller.py b/backend/app/api/v1/module_system/params/controller.py index 66d99ec9..4ba5a5ab 100644 --- a/backend/app/api/v1/module_system/params/controller.py +++ b/backend/app/api/v1/module_system/params/controller.py @@ -4,7 +4,6 @@ from fastapi import APIRouter, Body, Depends, Path, Query, Request, UploadFile from fastapi.responses import JSONResponse, StreamingResponse from redis.asyncio.client import Redis - from app.common.request import PaginationService from app.common.response import StreamResponse, SuccessResponse from app.utils.common_util import bytes2file_response @@ -12,6 +11,7 @@ from app.core.base_params import PaginationQueryParam from app.core.dependencies import AuthPermission, redis_getter from app.core.router_class import OperationLogRoute from app.core.logger import logger + from ..auth.schema import AuthSchema from .param import ParamsQueryParam from .schema import ParamsCreateSchema, ParamsUpdateSchema diff --git a/backend/app/api/v1/module_system/params/crud.py b/backend/app/api/v1/module_system/params/crud.py index eaa78e7e..ff6d7f0f 100644 --- a/backend/app/api/v1/module_system/params/crud.py +++ b/backend/app/api/v1/module_system/params/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from ..auth.schema import AuthSchema from .model import ParamsModel from .schema import ParamsCreateSchema, ParamsUpdateSchema diff --git a/backend/app/api/v1/module_system/params/param.py b/backend/app/api/v1/module_system/params/param.py index a936c361..1cf1e5b4 100644 --- a/backend/app/api/v1/module_system/params/param.py +++ b/backend/app/api/v1/module_system/params/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class ParamsQueryParam: """配置管理查询参数""" diff --git a/backend/app/api/v1/module_system/params/service.py b/backend/app/api/v1/module_system/params/service.py index c1564fc3..6e19ad8a 100644 --- a/backend/app/api/v1/module_system/params/service.py +++ b/backend/app/api/v1/module_system/params/service.py @@ -8,13 +8,14 @@ from fastapi import UploadFile from redis.asyncio.client import Redis from app.common.enums import RedisInitKeyConfig -from app.core.database import AsyncSessionLocal +from app.core.database import async_db_session from app.core.redis_crud import RedisCURD from app.utils.excel_util import ExcelUtil from app.utils.upload_util import UploadUtil from app.core.base_schema import UploadResponseSchema from app.core.exceptions import CustomException from app.core.logger import logger + from ..auth.schema import AuthSchema from .param import ParamsQueryParam from .schema import ParamsOutSchema, ParamsUpdateSchema, ParamsCreateSchema @@ -276,7 +277,7 @@ class ParamsService: 返回: - None """ - async with AsyncSessionLocal() as session: + async with async_db_session() as session: async with session.begin(): auth = AuthSchema(db=session) config_obj = await ParamsCRUD(auth).get_obj_list_crud() diff --git a/backend/app/api/v1/module_system/position/controller.py b/backend/app/api/v1/module_system/position/controller.py index bec0dae0..57a9a37d 100644 --- a/backend/app/api/v1/module_system/position/controller.py +++ b/backend/app/api/v1/module_system/position/controller.py @@ -11,6 +11,7 @@ from app.core.router_class import OperationLogRoute from app.core.dependencies import AuthPermission from app.core.base_schema import BatchSetAvailable from app.core.logger import logger + from ..auth.schema import AuthSchema from .service import PositionService from .param import PositionQueryParam diff --git a/backend/app/api/v1/module_system/position/param.py b/backend/app/api/v1/module_system/position/param.py index c28ddfb2..f28f80a6 100644 --- a/backend/app/api/v1/module_system/position/param.py +++ b/backend/app/api/v1/module_system/position/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class PositionQueryParam: """岗位管理查询参数""" diff --git a/backend/app/api/v1/module_system/position/schema.py b/backend/app/api/v1/module_system/position/schema.py index 479dcbd7..59825d46 100644 --- a/backend/app/api/v1/module_system/position/schema.py +++ b/backend/app/api/v1/module_system/position/schema.py @@ -4,7 +4,7 @@ from typing import Optional from pydantic import BaseModel, ConfigDict, Field, field_validator from app.core.base_schema import BaseSchema -from app.core.validator import DateTimeStr + class PositionCreateSchema(BaseModel): """岗位创建模型""" diff --git a/backend/app/api/v1/module_system/position/service.py b/backend/app/api/v1/module_system/position/service.py index 80b9c36a..3ca0f2cf 100644 --- a/backend/app/api/v1/module_system/position/service.py +++ b/backend/app/api/v1/module_system/position/service.py @@ -5,6 +5,7 @@ from typing import Any, Dict, List, Optional from app.core.base_schema import BatchSetAvailable from app.core.exceptions import CustomException from app.utils.excel_util import ExcelUtil + from ..auth.schema import AuthSchema from .param import PositionQueryParam from .crud import PositionCRUD diff --git a/backend/app/api/v1/module_system/role/controller.py b/backend/app/api/v1/module_system/role/controller.py index 71efa86e..5ddaab90 100644 --- a/backend/app/api/v1/module_system/role/controller.py +++ b/backend/app/api/v1/module_system/role/controller.py @@ -11,6 +11,7 @@ from app.core.base_params import PaginationQueryParam from app.core.dependencies import AuthPermission from app.core.base_schema import BatchSetAvailable from app.core.logger import logger + from ..auth.schema import AuthSchema from .service import RoleService from .param import RoleQueryParam diff --git a/backend/app/api/v1/module_system/role/crud.py b/backend/app/api/v1/module_system/role/crud.py index b8938e97..5ca92011 100644 --- a/backend/app/api/v1/module_system/role/crud.py +++ b/backend/app/api/v1/module_system/role/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Sequence, Optional, Union, Any from app.core.base_crud import CRUDBase + from .model import RoleModel from .schema import RoleCreateSchema, RoleUpdateSchema from ..auth.schema import AuthSchema diff --git a/backend/app/api/v1/module_system/role/model.py b/backend/app/api/v1/module_system/role/model.py index 32c2c638..360edc6a 100644 --- a/backend/app/api/v1/module_system/role/model.py +++ b/backend/app/api/v1/module_system/role/model.py @@ -5,7 +5,6 @@ """ from typing import Optional, List, TYPE_CHECKING - from sqlalchemy import Boolean, String, Integer, ForeignKey from sqlalchemy.orm import relationship, Mapped, mapped_column diff --git a/backend/app/api/v1/module_system/role/param.py b/backend/app/api/v1/module_system/role/param.py index 4d6ea717..5c565a21 100644 --- a/backend/app/api/v1/module_system/role/param.py +++ b/backend/app/api/v1/module_system/role/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class RoleQueryParam: """角色管理查询参数""" diff --git a/backend/app/api/v1/module_system/role/schema.py b/backend/app/api/v1/module_system/role/schema.py index e0a137c0..53819e4d 100644 --- a/backend/app/api/v1/module_system/role/schema.py +++ b/backend/app/api/v1/module_system/role/schema.py @@ -6,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator, field_valida from app.core.base_schema import BaseSchema from app.core.validator import role_permission_request_validator from app.core.validator import DateTimeStr + from ..dept.schema import DeptOutSchema from ..menu.schema import MenuOutSchema diff --git a/backend/app/api/v1/module_system/role/service.py b/backend/app/api/v1/module_system/role/service.py index be777aa4..bc0af57d 100644 --- a/backend/app/api/v1/module_system/role/service.py +++ b/backend/app/api/v1/module_system/role/service.py @@ -5,6 +5,7 @@ from typing import Any, Dict, List, Optional from app.core.base_schema import BatchSetAvailable from app.core.exceptions import CustomException from app.utils.excel_util import ExcelUtil + from ..auth.schema import AuthSchema from .crud import RoleCRUD from .param import RoleQueryParam diff --git a/backend/app/api/v1/module_system/tenant/controller.py b/backend/app/api/v1/module_system/tenant/controller.py index 12b2b0e2..f4ec83e2 100644 --- a/backend/app/api/v1/module_system/tenant/controller.py +++ b/backend/app/api/v1/module_system/tenant/controller.py @@ -11,6 +11,7 @@ from app.core.dependencies import AuthPermission from app.core.router_class import OperationLogRoute from app.core.base_schema import BatchSetAvailable from app.core.logger import logger + from app.api.v1.module_system.auth.schema import AuthSchema from .param import TenantQueryParam from .service import TenantService diff --git a/backend/app/api/v1/module_system/tenant/crud.py b/backend/app/api/v1/module_system/tenant/crud.py index 1c627b67..d8baa52a 100644 --- a/backend/app/api/v1/module_system/tenant/crud.py +++ b/backend/app/api/v1/module_system/tenant/crud.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional, Sequence, Union, Any from app.core.base_crud import CRUDBase + from app.api.v1.module_system.auth.schema import AuthSchema from .model import TenantModel from .schema import TenantCreateSchema, TenantUpdateSchema, TenantOutSchema diff --git a/backend/app/api/v1/module_system/tenant/param.py b/backend/app/api/v1/module_system/tenant/param.py index c70094db..c1d3b550 100644 --- a/backend/app/api/v1/module_system/tenant/param.py +++ b/backend/app/api/v1/module_system/tenant/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class TenantQueryParam: """租户查询参数""" diff --git a/backend/app/api/v1/module_system/tenant/service.py b/backend/app/api/v1/module_system/tenant/service.py index 9366cced..da9d6bd1 100644 --- a/backend/app/api/v1/module_system/tenant/service.py +++ b/backend/app/api/v1/module_system/tenant/service.py @@ -9,6 +9,7 @@ from app.core.base_schema import BatchSetAvailable from app.core.exceptions import CustomException from app.utils.excel_util import ExcelUtil from app.core.logger import logger + from app.api.v1.module_system.auth.schema import AuthSchema from .schema import TenantCreateSchema, TenantUpdateSchema, TenantOutSchema from .param import TenantQueryParam diff --git a/backend/app/api/v1/module_system/user/controller.py b/backend/app/api/v1/module_system/user/controller.py index 68afa587..b701eb16 100644 --- a/backend/app/api/v1/module_system/user/controller.py +++ b/backend/app/api/v1/module_system/user/controller.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- +import urllib.parse from fastapi import APIRouter, Depends, Body, Path, Query, Form, File, UploadFile, Request from fastapi.responses import JSONResponse, StreamingResponse from sqlalchemy.ext.asyncio import AsyncSession -import urllib.parse from app.common.response import StreamResponse, SuccessResponse from app.common.request import PaginationService @@ -13,6 +13,7 @@ from app.core.dependencies import db_getter, get_current_user, AuthPermission from app.core.base_params import PaginationQueryParam from app.core.base_schema import BatchSetAvailable from app.core.logger import logger + from ..auth.schema import AuthSchema from .service import UserService from .param import UserQueryParam diff --git a/backend/app/api/v1/module_system/user/crud.py b/backend/app/api/v1/module_system/user/crud.py index 02bdedfd..ffca6849 100644 --- a/backend/app/api/v1/module_system/user/crud.py +++ b/backend/app/api/v1/module_system/user/crud.py @@ -4,13 +4,13 @@ from typing import Dict, List, Optional, Sequence, Union, Any from datetime import datetime from app.core.base_crud import CRUDBase + +from app.api.v1.module_system.auth.schema import AuthSchema from .model import UserModel from .schema import UserCreateSchema, UserForgetPasswordSchema, UserUpdateSchema from ..role.crud import RoleCRUD from ..position.crud import PositionCRUD -from app.api.v1.module_system.auth.schema import AuthSchema - class UserCRUD(CRUDBase[UserModel, UserCreateSchema, UserUpdateSchema]): """用户模块数据层""" diff --git a/backend/app/api/v1/module_system/user/model.py b/backend/app/api/v1/module_system/user/model.py index 90d53643..7317c22a 100644 --- a/backend/app/api/v1/module_system/user/model.py +++ b/backend/app/api/v1/module_system/user/model.py @@ -6,14 +6,14 @@ from datetime import datetime from typing import Optional, List - from sqlalchemy import Boolean, String, Integer, DateTime, ForeignKey, Text from sqlalchemy.orm import relationship, Mapped, mapped_column +from app.core.base_model import MappedBase + from app.api.v1.module_system.dept.model import DeptModel from app.api.v1.module_system.position.model import PositionModel from app.api.v1.module_system.role.model import RoleModel -from app.core.base_model import MappedBase class UserRolesModel(MappedBase): diff --git a/backend/app/api/v1/module_system/user/param.py b/backend/app/api/v1/module_system/user/param.py index 116e64e1..bf48eb2c 100644 --- a/backend/app/api/v1/module_system/user/param.py +++ b/backend/app/api/v1/module_system/user/param.py @@ -5,6 +5,7 @@ from fastapi import Query from app.core.validator import DateTimeStr + class UserQueryParam: """用户管理查询参数""" diff --git a/backend/app/api/v1/module_system/user/schema.py b/backend/app/api/v1/module_system/user/schema.py index 9084f5cb..1a8b56ff 100644 --- a/backend/app/api/v1/module_system/user/schema.py +++ b/backend/app/api/v1/module_system/user/schema.py @@ -2,11 +2,13 @@ from typing import Optional, List from pydantic import BaseModel, ConfigDict, Field, EmailStr, field_validator +from urllib.parse import urlparse from app.core.validator import DateTimeStr, mobile_validator from app.core.base_schema import BaseSchema, CommonSchema + from app.api.v1.module_system.role.schema import RoleOutSchema -from urllib.parse import urlparse + class CurrentUserUpdateSchema(BaseModel): """基础用户信息""" diff --git a/backend/app/api/v1/module_system/user/service.py b/backend/app/api/v1/module_system/user/service.py index 6c885316..6d504944 100644 --- a/backend/app/api/v1/module_system/user/service.py +++ b/backend/app/api/v1/module_system/user/service.py @@ -12,6 +12,7 @@ from app.core.logger import logger from app.utils.common_util import traversal_to_tree from app.utils.excel_util import ExcelUtil from app.utils.upload_util import UploadUtil + from ..position.crud import PositionCRUD from ..role.crud import RoleCRUD from ..menu.crud import MenuCRUD diff --git a/backend/app/common/constant.py b/backend/app/common/constant.py index 81b245f7..a8f33e87 100644 --- a/backend/app/common/constant.py +++ b/backend/app/common/constant.py @@ -1,8 +1,10 @@ # -*- coding: utf-8 -*- from enum import Enum + from app.config.setting import settings + class RET(Enum): """ 系统返回码枚举 diff --git a/backend/app/core/ap_scheduler.py b/backend/app/core/ap_scheduler.py index c25358d9..4dca25f3 100644 --- a/backend/app/core/ap_scheduler.py +++ b/backend/app/core/ap_scheduler.py @@ -3,7 +3,6 @@ import json import importlib from datetime import datetime -from sqlalchemy.orm.session import Session from typing import Union, List, Any, Optional from asyncio import iscoroutinefunction from apscheduler.job import Job @@ -19,13 +18,13 @@ from apscheduler.triggers.date import DateTrigger from apscheduler.triggers.interval import IntervalTrigger from concurrent.futures import ThreadPoolExecutor -from app.api.v1.module_application.job.model import JobModel from app.config.setting import settings -from app.core.database import SessionLocal, AsyncSessionLocal, engine +from app.core.database import engine, db_session, async_db_session from app.core.exceptions import CustomException from app.core.logger import logger from app.utils.cron_util import CronUtil +from app.api.v1.module_application.job.model import JobModel job_stores = { 'default': MemoryJobStore(), @@ -138,7 +137,7 @@ class SchedulerUtil: 返回: - None """ - with SessionLocal() as session: + with db_session() as session: try: session.add(job_log) session.commit() @@ -161,7 +160,7 @@ class SchedulerUtil: from app.api.v1.module_system.auth.schema import AuthSchema logger.info('🔎 开始启动定时任务...') scheduler.start() - async with AsyncSessionLocal() as session: + async with async_db_session() as session: async with session.begin(): auth = AuthSchema(db=session) job_list = await JobCRUD(auth).get_obj_list_crud() diff --git a/backend/app/core/base_crud.py b/backend/app/core/base_crud.py index feeade26..9969ca01 100644 --- a/backend/app/core/base_crud.py +++ b/backend/app/core/base_crud.py @@ -9,14 +9,15 @@ from sqlalchemy import asc, func, select, delete, Select, desc, update, or_, and from sqlalchemy import inspect as sa_inspect from app.core.base_model import MappedBase -from app.api.v1.module_system.auth.schema import AuthSchema -from app.api.v1.module_system.dept.model import DeptModel -from app.api.v1.module_system.user.model import UserModel from app.utils.common_util import get_child_id_map, get_child_recursion from app.core.exceptions import CustomException from app.common.request import PageResultSchema from app.core.serialize import Serialize +from app.api.v1.module_system.auth.schema import AuthSchema +from app.api.v1.module_system.dept.model import DeptModel +from app.api.v1.module_system.user.model import UserModel + ModelType = TypeVar("ModelType", bound=MappedBase) CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) diff --git a/backend/app/core/database.py b/backend/app/core/database.py index 752b97e2..49dd4381 100644 --- a/backend/app/core/database.py +++ b/backend/app/core/database.py @@ -5,65 +5,84 @@ from redis import exceptions from fastapi import FastAPI from sqlalchemy import create_engine, Engine from sqlalchemy.orm import sessionmaker -from sqlalchemy.ext.asyncio import ( - create_async_engine, - async_sessionmaker, - AsyncSession, - AsyncEngine -) +from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession, AsyncEngine from app.core.logger import logger from app.config.setting import settings from app.core.exceptions import CustomException -# 同步数据库引擎 -engine: Engine = create_engine( - url=settings.DB_URI, - echo=settings.DATABASE_ECHO, - pool_pre_ping=settings.POOL_PRE_PING, - pool_recycle=settings.POOL_RECYCLE, -) - -# 同步数据库会话工厂 -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - -# 异步数据库引擎 -async_engine: AsyncEngine = create_async_engine( - url=settings.ASYNC_DB_URI, - echo=settings.DATABASE_ECHO, - echo_pool=settings.ECHO_POOL, - pool_pre_ping=settings.POOL_PRE_PING, - future=settings.FUTURE, - pool_recycle=settings.POOL_RECYCLE, - pool_size=settings.POOL_SIZE, - max_overflow=settings.MAX_OVERFLOW, - pool_timeout=settings.POOL_TIMEOUT, - pool_use_lifo=settings.POOL_USE_LIFO, -) - -# 异步数据库会话工厂 -AsyncSessionLocal = async_sessionmaker( - bind=async_engine, - autocommit=settings.AUTOCOMMIT, - autoflush=settings.AUTOFETCH, - expire_on_commit=settings.EXPIRE_ON_COMMIT, - class_=AsyncSession -) - -def session_connect() -> AsyncSession: +def create_engine_and_session( + db_url: str = settings.DB_URI +) -> tuple[Engine, sessionmaker]: """ - 获取异步数据库会话连接。 + 创建同步数据库引擎和会话工厂。 + + 参数: + - db_url (str): 数据库连接URL,默认从配置中获取。 返回: - - AsyncSession: 异步数据库会话连接。 + - tuple[Engine, sessionmaker]: 同步数据库引擎和会话工厂。 """ try: if not settings.SQL_DB_ENABLE: raise CustomException(msg="请先开启数据库连接", data="请启用 app/config/setting.py: SQL_DB_ENABLE") - return AsyncSessionLocal() + # 同步数据库引擎 + engine: Engine = create_engine( + url=db_url, + echo=settings.DATABASE_ECHO, + pool_pre_ping=settings.POOL_PRE_PING, + pool_recycle=settings.POOL_RECYCLE, + ) except Exception as e: - raise CustomException(msg=f"数据库连接失败: {e}") + logger.error(f'❌ 数据库连接失败 {e}') + raise + else: + # 同步数据库会话工厂 + SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + return engine, SessionLocal + +def create_async_engine_and_session( + db_url: str = settings.ASYNC_DB_URI +) -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]: + """ + 获取异步数据库会话连接。 + + 返回: + - tuple[AsyncEngine, async_sessionmaker[AsyncSession]]: 异步数据库引擎和会话工厂。 + """ + try: + if not settings.SQL_DB_ENABLE: + raise CustomException(msg="请先开启数据库连接", data="请启用 app/config/setting.py: SQL_DB_ENABLE") + # 异步数据库引擎 + async_engine: AsyncEngine = create_async_engine( + url=db_url, + echo=settings.DATABASE_ECHO, + echo_pool=settings.ECHO_POOL, + pool_pre_ping=settings.POOL_PRE_PING, + future=settings.FUTURE, + pool_recycle=settings.POOL_RECYCLE, + pool_size=settings.POOL_SIZE, + max_overflow=settings.MAX_OVERFLOW, + pool_timeout=settings.POOL_TIMEOUT, + pool_use_lifo=settings.POOL_USE_LIFO, + ) + except Exception as e: + logger.error(f'❌ 数据库连接失败 {e}') + raise + else: + # 异步数据库会话工厂 + AsyncSessionLocal = async_sessionmaker( + bind=async_engine, + autocommit=settings.AUTOCOMMIT, + autoflush=settings.AUTOFETCH, + expire_on_commit=settings.EXPIRE_ON_COMMIT, + class_=AsyncSession + ) + return async_engine, AsyncSessionLocal + +engine, db_session = create_engine_and_session(settings.DB_URI) +async_engine, async_db_session = create_async_engine_and_session(settings.ASYNC_DB_URI) async def redis_connect(app: FastAPI, status: bool) -> Redis | None: """ @@ -93,13 +112,15 @@ async def redis_connect(app: FastAPI, status: bool) -> Redis | None: if await rd.ping(): logger.info("✅️ Redis连接成功...") return rd - raise CustomException(msg="Redis连接失败") except exceptions.AuthenticationError as e: - raise exceptions.AuthenticationError(f"Redis认证失败: {e}") + logger.error(f"❌ 数据库 Redis 认证失败: {e}") + raise except exceptions.TimeoutError as e: - raise exceptions.TimeoutError(f"Redis连接超时: {e}") + logger.error(f"❌ 数据库 Redis 连接超时: {e}") + raise except exceptions.RedisError as e: - raise exceptions.RedisError(f"Redis连接错误: {e}") + logger.error(f"❌ 数据库 Redis 连接错误: {e}") + raise else: await app.state.redis.close() logger.info('✅️ Redis连接已关闭') diff --git a/backend/app/core/dependencies.py b/backend/app/core/dependencies.py index 24744b66..377244b9 100644 --- a/backend/app/core/dependencies.py +++ b/backend/app/core/dependencies.py @@ -8,15 +8,16 @@ from typing import AsyncGenerator, Optional from fastapi import Depends, Request from fastapi import Depends +from app.common.enums import RedisInitKeyConfig +from app.core.exceptions import CustomException +from app.core.database import async_db_session +from app.core.redis_crud import RedisCURD +from app.core.security import OAuth2Schema, decode_access_token +from app.core.logger import logger + from app.api.v1.module_system.user.schema import UserOutSchema from app.api.v1.module_system.user.model import UserModel from app.api.v1.module_system.role.model import RoleModel -from app.common.enums import RedisInitKeyConfig -from app.core.exceptions import CustomException -from app.core.database import session_connect -from app.core.security import OAuth2Schema, decode_access_token -from app.core.logger import logger -from app.core.redis_crud import RedisCURD from app.api.v1.module_system.user.crud import UserCRUD from app.api.v1.module_system.auth.schema import AuthSchema @@ -27,7 +28,7 @@ async def db_getter() -> AsyncGenerator[AsyncSession, None]: 返回: - AsyncSession: 数据库会话连接 """ - async with session_connect() as session: + async with async_db_session() as session: async with session.begin(): yield session diff --git a/backend/app/core/discover.py b/backend/app/core/discover.py index 7b9784c1..b3622c78 100644 --- a/backend/app/core/discover.py +++ b/backend/app/core/discover.py @@ -17,7 +17,7 @@ from __future__ import annotations import importlib from pathlib import Path -from typing import Dict, Iterable, Optional, Set, Tuple, List +from typing import Dict, Iterable, Optional, Set, Tuple from fastapi import APIRouter diff --git a/backend/app/core/logger.py b/backend/app/core/logger.py index d04312fb..61914f0b 100644 --- a/backend/app/core/logger.py +++ b/backend/app/core/logger.py @@ -6,7 +6,7 @@ from pathlib import Path from loguru import logger from app.config.setting import settings -from app.utils.common_util import worship + class InterceptHandler(logging.Handler): """ diff --git a/backend/app/core/middlewares.py b/backend/app/core/middlewares.py index da4d5355..8ef34e2d 100644 --- a/backend/app/core/middlewares.py +++ b/backend/app/core/middlewares.py @@ -1,7 +1,6 @@ # -*- coding: utf-8 -*- import time -import json from typing import Any from starlette.middleware.cors import CORSMiddleware from starlette.types import ASGIApp @@ -14,6 +13,7 @@ from app.common.response import ErrorResponse from app.config.setting import settings from app.core.logger import logger from app.core.exceptions import CustomException + from app.api.v1.module_system.params.service import ParamsService @@ -41,12 +41,15 @@ class RequestLogMiddleware(BaseHTTPMiddleware): self, request: Request, call_next: RequestResponseEndpoint ) -> Response: start_time = time.time() - - # 构建请求日志信息 - request_info = f"请求方法: {request.method}, 请求路径: {request.url.path}" - if request.client: - request_info = f"请求来源: {request.client.host}, {request_info}" - logger.info(request_info) + session_id = request.scope.get('session_id') + # 组装请求日志字段 + log_fields = [ + f"会话ID: {session_id}", + f"请求来源: {request.client.host if request.client else '未知'}", + f"请求方法: {request.method}", + f"请求路径: {request.url.path}", + ] + logger.info(log_fields) try: # 初始化响应变量 @@ -116,13 +119,12 @@ class RequestLogMiddleware(BaseHTTPMiddleware): response.headers["X-Process-Time"] = str(process_time) # 构建响应日志信息 - session_id = request.scope.get('session_id') + content_length = response.headers.get('content-length', '0') response_info = ( - f"会话ID: {session_id}, " f"响应状态: {response.status_code}, " f"响应内容长度: {content_length}, " - f"处理时间: {process_time}s" + f"处理时间: {process_time * 1000}ms" ) logger.info(response_info) diff --git a/backend/app/core/router_class.py b/backend/app/core/router_class.py index fa90924a..afcc3ccb 100644 --- a/backend/app/core/router_class.py +++ b/backend/app/core/router_class.py @@ -7,9 +7,10 @@ from fastapi.routing import APIRoute from user_agents import parse import json -from app.core.database import session_connect +from app.core.database import async_db_session from app.config.setting import settings from app.utils.ip_local_util import IpLocalUtil + from app.api.v1.module_system.auth.schema import AuthSchema from app.api.v1.module_system.log.schema import OperationLogCreateSchema from app.api.v1.module_system.log.service import OperationLogService @@ -121,7 +122,7 @@ class OperationLogRoute(APIRoute): # 如果请求来自api文档,则不记录日志 pass else: - async with session_connect() as session: + async with async_db_session() as session: async with session.begin(): auth = AuthSchema(db=session) await OperationLogService.create_log_service(data=OperationLogCreateSchema( diff --git a/backend/app/core/security.py b/backend/app/core/security.py index 36a0bd44..2b589763 100644 --- a/backend/app/core/security.py +++ b/backend/app/core/security.py @@ -8,6 +8,7 @@ from fastapi.security.utils import get_authorization_scheme_param from app.core.exceptions import CustomException from app.config.setting import settings + from app.api.v1.module_system.auth.schema import JWTPayloadSchema diff --git a/backend/app/plugin/init_app.py b/backend/app/plugin/init_app.py index 570a5149..0625a2d4 100644 --- a/backend/app/plugin/init_app.py +++ b/backend/app/plugin/init_app.py @@ -14,11 +14,12 @@ from fastapi.openapi.docs import ( from app.config.setting import settings from app.core.ap_scheduler import SchedulerUtil from app.core.logger import logger -from app.utils.common_util import import_module, import_modules_async, worship +from app.utils.common_util import import_module, import_modules_async from app.utils.console import run as console_run from app.core.exceptions import handle_exception from app.core.discover import router from app.scripts.initialize import InitializeData + from app.api.v1.module_system.params.service import ParamsService from app.api.v1.module_system.dict.service import DictDataService diff --git a/backend/app/scripts/initialize.py b/backend/app/scripts/initialize.py index 406cf424..28cbbb2a 100644 --- a/backend/app/scripts/initialize.py +++ b/backend/app/scripts/initialize.py @@ -8,9 +8,10 @@ from sqlalchemy import select, func from sqlalchemy.ext.asyncio import AsyncSession from app.core.logger import logger -from app.core.database import AsyncSessionLocal, async_engine +from app.core.database import async_db_session, async_engine from app.core.base_model import MappedBase from app.config.setting import settings + from app.api.v1.module_system.user.model import UserModel, UserRolesModel from app.api.v1.module_system.role.model import RoleModel from app.api.v1.module_system.dept.model import DeptModel @@ -159,7 +160,7 @@ class InitializeData: await self.__init_create_table() # 再初始化数据 - async with AsyncSessionLocal() as session: + async with async_db_session() as session: async with session.begin(): await self.__init_data(session) # 确保提交事务 diff --git a/backend/app/utils/gen_util.py b/backend/app/utils/gen_util.py index e7d7fdc4..346a068a 100644 --- a/backend/app/utils/gen_util.py +++ b/backend/app/utils/gen_util.py @@ -5,6 +5,7 @@ from typing import List from app.common.constant import GenConstant from app.utils.string_util import StringUtil + from app.api.v1.module_generator.gencode.schema import GenTableOutSchema, GenTableSchema, GenTableColumnSchema diff --git a/backend/app/utils/jinja2_template_util.py b/backend/app/utils/jinja2_template_util.py index ee630ef1..4eef0371 100644 --- a/backend/app/utils/jinja2_template_util.py +++ b/backend/app/utils/jinja2_template_util.py @@ -1,6 +1,5 @@ # -*- coding:utf-8 -*- -import json import os from datetime import datetime from jinja2.environment import Environment @@ -9,10 +8,11 @@ from typing import List, Any, Set from app.common.constant import GenConstant from app.config.setting import settings -from app.api.v1.module_generator.gencode.schema import GenTableOutSchema, GenTableColumnOutSchema from app.utils.common_util import CamelCaseUtil, SnakeCaseUtil from app.utils.string_util import StringUtil +from app.api.v1.module_generator.gencode.schema import GenTableOutSchema, GenTableColumnOutSchema + class Jinja2TemplateUtil: """ @@ -107,7 +107,7 @@ class Jinja2TemplateUtil: 'function_name': function_name if StringUtil.is_not_empty(function_name) else '【请填写功能名称】', 'class_name': class_name, 'module_name': module_name, - 'business_name': business_name.capitalize(), + 'business_name': business_name, 'base_package': cls.get_package_prefix(package_name), 'package_name': package_name, 'datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), diff --git a/backend/requirements.txt b/backend/requirements.txt index a1a09e70..22b55c0a 100755 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -33,4 +33,9 @@ openai==1.55.2 # ai 大模型 rich==13.9.4 # 终端打印美化 sqlglot[rs]==27.8.0 # sql 解析 pydantic_validation_decorator==0.1.4 # 模型验证 -loguru==0.7.3 \ No newline at end of file +loguru==0.7.3 + +# amqp==5.3.1 +# fastapi-limiter==0.1.6 +# fastapi-pagination==0.15.0 +# python-socketio==5.14.3 \ No newline at end of file