style: 优化代码格式和导入顺序

refactor: 重构数据库连接模块,提高可维护性

docs: 更新README.md项目描述

style: 调整日志输出格式和内容

refactor: 优化中间件日志记录逻辑

style: 统一代码中的空行和导入顺序

refactor: 分离数据库引擎和会话创建逻辑

style: 清理未使用的导入和代码

refactor: 重命名数据库会话变量

style: 调整jinja2模板变量命名

refactor: 优化异常处理和日志记录

style: 统一字符串格式化方式

refactor: 优化redis连接错误处理

style: 调整注释格式和位置

refactor: 优化数据库连接配置

style: 清理多余空行和注释
This commit is contained in:
zhangtao
2025-11-16 18:43:30 +08:00
parent e24e54bfee
commit fce6333722
92 changed files with 216 additions and 115 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# FastApiAdmin - Backend
一个基于 FastAPI 的现代化后端管理系统,为前端 Vue3 管理系统提供完整的 API 服务支持。
一个基于 FastAPI 框架构建企业级后端架构解决方案,为前端 Vue3 管理系统提供完整的 API 服务支持。
## 🚀 项目特性
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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):
@@ -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
@@ -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"]))])
@@ -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
@@ -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:
"""
文件管理服务层
@@ -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
@@ -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
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class DemoQueryParam:
"""示例查询参数"""
@@ -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
@@ -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
@@ -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
@@ -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
+1
View File
@@ -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
+1
View File
@@ -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
@@ -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
@@ -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=["资源管理"])
@@ -3,6 +3,7 @@
from typing import Optional
from fastapi import Query
class ResourceSearchQueryParam:
"""资源搜索查询参数"""
@@ -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
@@ -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,
@@ -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
@@ -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,
@@ -17,6 +17,7 @@ from app.core.dependencies import (
get_current_user,
redis_getter
)
from .service import (
LoginService,
CaptchaService
@@ -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
@@ -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
@@ -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
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class DeptQueryParam:
"""部门管理查询参数"""
@@ -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
@@ -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
@@ -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
@@ -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()
@@ -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
@@ -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
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class OperationLogQueryParam:
"""操作日志查询参数"""
@@ -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):
@@ -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
@@ -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
@@ -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
@@ -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
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class MenuQueryParam:
"""菜单管理查询参数"""
@@ -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
@@ -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
@@ -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
@@ -5,7 +5,6 @@
"""
from typing import Optional
from sqlalchemy import Boolean, String, Text
from sqlalchemy.orm import Mapped, mapped_column
@@ -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
@@ -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
@@ -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
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class ParamsQueryParam:
"""配置管理查询参数"""
@@ -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()
@@ -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
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class PositionQueryParam:
"""岗位管理查询参数"""
@@ -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):
"""岗位创建模型"""
@@ -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
@@ -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
@@ -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
@@ -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
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class RoleQueryParam:
"""角色管理查询参数"""
@@ -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
@@ -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
@@ -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
@@ -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
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class TenantQueryParam:
"""租户查询参数"""
@@ -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
@@ -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
@@ -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]):
"""用户模块数据层"""
@@ -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):
@@ -5,6 +5,7 @@ from fastapi import Query
from app.core.validator import DateTimeStr
class UserQueryParam:
"""用户管理查询参数"""
@@ -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):
"""基础用户信息"""
@@ -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
+2
View File
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-
from enum import Enum
from app.config.setting import settings
class RET(Enum):
"""
系统返回码枚举
+4 -5
View File
@@ -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()
+4 -3
View File
@@ -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)
+48 -27
View File
@@ -5,32 +5,58 @@ 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
def create_engine_and_session(
db_url: str = settings.DB_URI
) -> tuple[Engine, sessionmaker]:
"""
创建同步数据库引擎和会话工厂
参数:
- db_url (str): 数据库连接URL,默认从配置中获取
返回:
- tuple[Engine, sessionmaker]: 同步数据库引擎和会话工厂
"""
try:
if not settings.SQL_DB_ENABLE:
raise CustomException(msg="请先开启数据库连接", data="请启用 app/config/setting.py: SQL_DB_ENABLE")
# 同步数据库引擎
engine: Engine = create_engine(
url=settings.DB_URI,
url=db_url,
echo=settings.DATABASE_ECHO,
pool_pre_ping=settings.POOL_PRE_PING,
pool_recycle=settings.POOL_RECYCLE,
)
except Exception as 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=settings.ASYNC_DB_URI,
url=db_url,
echo=settings.DATABASE_ECHO,
echo_pool=settings.ECHO_POOL,
pool_pre_ping=settings.POOL_PRE_PING,
@@ -41,7 +67,10 @@ async_engine: AsyncEngine = create_async_engine(
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,
@@ -50,20 +79,10 @@ AsyncSessionLocal = async_sessionmaker(
expire_on_commit=settings.EXPIRE_ON_COMMIT,
class_=AsyncSession
)
return async_engine, AsyncSessionLocal
def session_connect() -> AsyncSession:
"""
获取异步数据库会话连接
返回:
- AsyncSession: 异步数据库会话连接
"""
try:
if not settings.SQL_DB_ENABLE:
raise CustomException(msg="请先开启数据库连接", data="请启用 app/config/setting.py: SQL_DB_ENABLE")
return AsyncSessionLocal()
except Exception as e:
raise CustomException(msg=f"数据库连接失败: {e}")
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连接已关闭')
+8 -7
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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):
"""
+12 -10
View File
@@ -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)
+3 -2
View File
@@ -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(
+1
View File
@@ -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
+2 -1
View File
@@ -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
+3 -2
View File
@@ -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)
# 确保提交事务
+1
View File
@@ -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
+3 -3
View File
@@ -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'),
+5
View File
@@ -34,3 +34,8 @@ rich==13.9.4 # 终端打印美化
sqlglot[rs]==27.8.0 # sql 解析
pydantic_validation_decorator==0.1.4 # 模型验证
loguru==0.7.3
# amqp==5.3.1
# fastapi-limiter==0.1.6
# fastapi-pagination==0.15.0
# python-socketio==5.14.3