upload project source code

This commit is contained in:
2026-04-30 18:49:43 +08:00
commit 9b394ba682
2277 changed files with 660945 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-

View File

@@ -0,0 +1,247 @@
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Body, Depends, Path, 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.core.router_class import OperationLogRoute
from app.utils.common_util import bytes2file_response
from app.core.base_params import PaginationQueryParam
from app.core.dependencies import AuthPermission, redis_getter
from app.core.logger import log
from app.core.exceptions import CustomException
from ..auth.schema import AuthSchema
from .schema import ParamsCreateSchema, ParamsUpdateSchema, ParamsQueryParam
from .service import ParamsService
ParamsRouter = APIRouter(route_class=OperationLogRoute, prefix="/param", tags=["参数管理"])
@ParamsRouter.get("/detail/{id}", summary="获取参数详情", description="获取参数详情")
async def get_type_detail_controller(
id: int = Path(..., description="参数ID"),
auth: AuthSchema = Depends(AuthPermission(["module_system:param:query"]))
) -> JSONResponse:
"""
获取参数详情
参数:
- id (int): 参数ID
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含参数详情的 JSON 响应
"""
result_dict = await ParamsService.get_obj_detail_service(id=id, auth=auth)
log.info(f"获取参数详情成功 {id}")
return SuccessResponse(data=result_dict, msg="获取参数详情成功")
@ParamsRouter.get("/key/{config_key}", summary="根据配置键获取参数详情", description="根据配置键获取参数详情")
async def get_obj_by_key_controller(
config_key: str = Path(..., description="配置键"),
auth: AuthSchema = Depends(AuthPermission(["module_system:param:query"]))
) -> JSONResponse:
"""
根据配置键获取参数详情
参数:
- config_key (str): 配置键
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含参数详情的 JSON 响应
"""
result_dict = await ParamsService.get_obj_by_key_service(config_key=config_key, auth=auth)
log.info(f"根据配置键获取参数详情成功 {config_key}")
return SuccessResponse(data=result_dict, msg="根据配置键获取参数详情成功")
@ParamsRouter.get("/value/{config_key}", summary="根据配置键获取参数值", description="根据配置键获取参数值")
async def get_config_value_by_key_controller(
config_key: str = Path(..., description="配置键"),
auth: AuthSchema = Depends(AuthPermission(["module_system:param:query"]))
) -> JSONResponse:
"""
根据配置键获取参数值
参数:
- config_key (str): 配置键
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含参数值的 JSON 响应
"""
result_value = await ParamsService.get_config_value_by_key_service(config_key=config_key, auth=auth)
log.info(f"根据配置键获取参数值成功 {config_key}")
return SuccessResponse(data=result_value, msg="根据配置键获取参数值成功")
@ParamsRouter.get("/list", summary="获取参数列表", description="获取参数列表")
async def get_obj_list_controller(
auth: AuthSchema = Depends(AuthPermission(["module_system:param:query"])),
page: PaginationQueryParam = Depends(),
search: ParamsQueryParam = Depends(),
) -> JSONResponse:
"""
获取参数列表
参数:
- auth (AuthSchema): 认证信息模型
- page (PaginationQueryParam): 分页查询参数模型
- search (ParamsQueryParam): 参数查询参数模型
返回:
- JSONResponse: 包含参数列表的 JSON 响应
"""
result_dict_list = await ParamsService.get_obj_list_service(auth=auth, search=search, order_by=page.order_by)
result_dict = await PaginationService.paginate(data_list= result_dict_list, page_no= page.page_no, page_size = page.page_size)
log.info(f"获取参数列表成功")
return SuccessResponse(data=result_dict, msg="查询参数列表成功")
@ParamsRouter.post("/create", summary="创建参数", description="创建参数")
async def create_obj_controller(
data: ParamsCreateSchema,
redis: Redis = Depends(redis_getter),
auth: AuthSchema = Depends(AuthPermission(["module_system:param:create"]))
) -> JSONResponse:
"""
创建参数
参数:
- data (ParamsCreateSchema): 参数创建模型
- redis (Redis): Redis 客户端实例
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含创建参数结果的 JSON 响应
"""
result_dict = await ParamsService.create_obj_service(auth=auth, redis=redis, data=data)
log.info(f"创建参数成功: {result_dict}")
return SuccessResponse(data=result_dict, msg="创建参数成功")
@ParamsRouter.put("/update/{id}", summary="修改参数", description="修改参数")
async def update_objs_controller(
data: ParamsUpdateSchema,
id: int = Path(..., description="参数ID"),
redis: Redis = Depends(redis_getter),
auth: AuthSchema = Depends(AuthPermission(["module_system:param:update"]))
) -> JSONResponse:
"""
修改参数
参数:
- data (ParamsUpdateSchema): 参数更新模型
- id (int): 参数ID
- redis (Redis): Redis 客户端实例
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含修改参数结果的 JSON 响应
"""
result_dict = await ParamsService.update_obj_service(auth=auth, redis=redis, id=id, data=data)
log.info(f"更新参数成功 {result_dict}")
return SuccessResponse(data=result_dict, msg="更新参数成功")
@ParamsRouter.delete("/delete", summary="删除参数", description="删除参数")
async def delete_obj_controller(
redis: Redis = Depends(redis_getter),
ids: list[int] = Body(..., description="ID列表"),
auth: AuthSchema = Depends(AuthPermission(["module_system:param:delete"]))
) -> JSONResponse:
"""
删除参数
参数:
- redis (Redis): Redis 客户端实例
- ids (list[int]): 参数ID列表
- auth (AuthSchema): 认证信息模型
返回:
- JSONResponse: 包含删除参数结果的 JSON 响应
"""
await ParamsService.delete_obj_service(auth=auth, redis=redis, ids=ids)
log.info(f"删除参数成功: {ids}")
return SuccessResponse(msg="删除参数成功")
@ParamsRouter.post('/export', summary="导出参数", description="导出参数")
async def export_obj_list_controller(
search: ParamsQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_system:param:export"]))
) -> StreamingResponse:
"""
导出参数
参数:
- search (ParamsQueryParam): 参数查询参数模型
- auth (AuthSchema): 认证信息模型
返回:
- StreamingResponse: 包含导出参数的 Excel 文件流响应
"""
result_dict_list = await ParamsService.get_obj_list_service(search=search, auth=auth)
export_result = await ParamsService.export_obj_service(data_list=result_dict_list)
log.info('导出参数成功')
return StreamResponse(
data=bytes2file_response(export_result),
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers = {
'Content-Disposition': 'attachment; filename=params.xlsx'
}
)
@ParamsRouter.post("/upload", summary="上传文件", description="上传文件到阿里云OSS", dependencies=[Depends(AuthPermission([]))])
async def upload_file_controller(
file: UploadFile
) -> JSONResponse:
"""
后台管理员上传文件到阿里云OSS
参数:
- file (UploadFile): 上传的文件对象
返回:
- JSONResponse: 包含上传文件结果的 JSON 响应
"""
if not file or not file.filename:
raise CustomException(msg="请选择要上传的文件")
log.info(f"开始上传文件: {file.filename}, 大小: {file.size} bytes")
try:
result_str = await ParamsService.upload_service(file=file)
log.info(f"文件上传成功: {file.filename}")
return SuccessResponse(data=result_str, msg='上传文件成功')
except CustomException as e:
log.error(f"文件上传失败: {file.filename}, 错误: {str(e)}")
raise
except Exception as e:
log.error(f"文件上传异常: {file.filename}, 错误: {str(e)}")
raise CustomException(msg="文件上传失败")
@ParamsRouter.get("/info", summary="获取初始化缓存参数", description="获取初始化缓存参数")
async def get_init_obj_controller(
redis: Redis = Depends(redis_getter),
) -> JSONResponse:
"""
获取初始化缓存参数
参数:
- redis (Redis): Redis 客户端实例
返回:
- JSONResponse: 获取初始化缓存参数的 JSON 响应
"""
result_dict = await ParamsService.get_init_config_service(redis=redis)
log.info(f"获取初始化缓存参数成功 {result_dict}")
return SuccessResponse(data=result_dict, msg="获取初始化缓存参数成功")

View File

@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
from typing import Sequence
from app.core.base_crud import CRUDBase
from ..auth.schema import AuthSchema
from .model import ParamsModel
from .schema import ParamsCreateSchema, ParamsUpdateSchema
class ParamsCRUD(CRUDBase[ParamsModel, ParamsCreateSchema, ParamsUpdateSchema]):
"""配置管理数据层"""
def __init__(self, auth: AuthSchema) -> None:
"""
初始化配置CRUD
参数:
- auth (AuthSchema): 认证信息模型
"""
self.auth = auth
super().__init__(model=ParamsModel, auth=auth)
async def get_obj_by_id_crud(self, id: int, preload: list | None = None) -> ParamsModel | None:
"""
获取配置管理型详情
参数:
- id (int): 配置管理型ID
- preload (list | None): 预加载关系,未提供时使用模型默认项
返回:
- ParamsModel | None: 配置管理型模型实例
"""
return await self.get(id=id, preload=preload)
async def get_obj_by_key_crud(self, key: str, preload: list | None = None) -> ParamsModel | None:
"""
根据key获取配置管理型详情
参数:
- key (str): 配置管理型key
- preload (list | None): 预加载关系,未提供时使用模型默认项
返回:
- ParamsModel | None: 配置管理型模型实例
"""
return await self.get(config_key=key, preload=preload)
async def get_obj_list_crud(self, search: dict | None = None, order_by: list | None = None, preload: list | None = None) -> Sequence[ParamsModel]:
"""
获取配置管理型列表
参数:
- search (dict | None): 查询参数对象。
- order_by (list | None): 排序参数列表。
- preload (list | None): 预加载关系,未提供时使用模型默认项
返回:
- Sequence[ParamsModel]: 配置管理型模型实例列表
"""
return await self.list(search=search, order_by=order_by, preload=preload)
async def create_obj_crud(self, data: ParamsCreateSchema) -> ParamsModel | None:
"""
创建配置管理型
参数:
- data (ParamsCreateSchema): 创建配置管理型负载模型
返回:
- ParamsModel | None: 配置管理型模型实例
"""
return await self.create(data=data)
async def update_obj_crud(self, id: int, data: ParamsUpdateSchema) -> ParamsModel | None:
"""
更新配置管理型
参数:
- id (int): 配置管理型ID
- data (ParamsUpdateSchema): 更新配置管理型负载模型
返回:
- ParamsModel | None: 配置管理型模型实例
"""
return await self.update(id=id, data=data)
async def delete_obj_crud(self, ids: list[int]) -> None:
"""
删除配置管理型
参数:
- ids (list[int]): 配置管理型ID列表
返回:
- None
"""
return await self.delete(ids=ids)

View File

@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from sqlalchemy import String, Boolean
from sqlalchemy.orm import Mapped, mapped_column
from app.core.base_model import ModelMixin
class ParamsModel(ModelMixin):
"""
参数配置表
"""
__tablename__: str = "sys_param"
__table_args__: dict[str, str] = ({'comment': '系统参数表'})
config_name: Mapped[str] = mapped_column(String(500), nullable=False, comment='参数名称')
config_key: Mapped[str] = mapped_column(String(500), nullable=False, comment='参数键名')
config_value: Mapped[str | None] = mapped_column(String(500), comment='参数键值')
config_type: Mapped[bool] = mapped_column(Boolean, default=False, nullable=True, comment="系统内置(True:是 False:否)")

View File

@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
from pydantic import BaseModel, ConfigDict, Field, field_validator
from fastapi import Query
from app.core.validator import DateTimeStr
from app.core.base_schema import BaseSchema
class ParamsCreateSchema(BaseModel):
"""配置创建模型"""
config_name: str = Field(..., max_length=64, description="参数名称")
config_key: str = Field(..., max_length=500, description="参数键名")
config_value: str | None = Field(default=None, description="参数键值")
config_type: bool = Field(default=False, description="系统内置(True:是 False:否)")
status: str = Field(default="0", description="状态(True:正常 False:停用)")
description: str | None = Field(default=None, max_length=500, description="描述")
@field_validator('config_key')
@classmethod
def _validate_config_key(cls, v: str) -> str:
v = v.strip().lower()
import re
if not re.match(r'^[a-z][a-z0-9_.-]*$', v):
raise ValueError('参数键名必须以小写字母开头,仅包含小写字母/数字/_.-')
return v
class ParamsUpdateSchema(ParamsCreateSchema):
"""配置更新模型"""
...
class ParamsOutSchema(ParamsCreateSchema, BaseSchema):
"""配置响应模型"""
model_config = ConfigDict(from_attributes=True)
class ParamsQueryParam:
"""配置管理查询参数"""
def __init__(
self,
config_name: str | None = Query(None, description="配置名称"),
config_key: str | None = Query(None, description="配置键名"),
config_type: bool | None = Query(None, description="系统内置((True:是 False:否))"),
created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
) -> None:
# 模糊查询字段
self.config_name = ("like", config_name)
self.config_key = ("like", config_key)
# 精确查询字段
self.config_type = config_type
# 时间范围查询
if created_time and len(created_time) == 2:
self.created_time = ("between", (created_time[0], created_time[1]))
if updated_time and len(updated_time) == 2:
self.updated_time = ("between", (updated_time[0], updated_time[1]))

View File

@@ -0,0 +1,396 @@
# -*- coding: utf-8 -*-
import json
from redis.asyncio.client import Redis
from fastapi import UploadFile
from redis.asyncio.client import Redis
from app.common.enums import RedisInitKeyConfig
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.utils.oss_util import OSSUtil
from app.core.base_schema import UploadResponseSchema
from app.core.exceptions import CustomException
from app.core.logger import log
from ..auth.schema import AuthSchema
from .schema import ParamsOutSchema, ParamsUpdateSchema, ParamsCreateSchema, ParamsQueryParam
from .crud import ParamsCRUD
class ParamsService:
"""
配置管理模块服务层
"""
@classmethod
async def get_obj_detail_service(cls, auth: AuthSchema, id: int) -> dict:
"""
获取配置详情
参数:
- auth (AuthSchema): 认证信息模型
- id (int): 配置管理型ID
返回:
- dict: 配置管理型模型实例字典表示
"""
obj = await ParamsCRUD(auth).get_obj_by_id_crud(id=id)
return ParamsOutSchema.model_validate(obj).model_dump()
@classmethod
async def get_obj_by_key_service(cls, auth: AuthSchema, config_key: str) -> dict:
"""
根据配置键获取配置详情
参数:
- auth (AuthSchema): 认证信息模型
- config_key (str): 配置管理型key
返回:
- Dict: 配置管理型模型实例字典表示
"""
obj = await ParamsCRUD(auth).get_obj_by_key_crud(key=config_key)
if not obj:
raise CustomException(msg=f'配置键 {config_key} 不存在')
return ParamsOutSchema.model_validate(obj).model_dump()
@classmethod
async def get_config_value_by_key_service(cls, auth: AuthSchema, config_key: str) -> str | None:
"""
根据配置键获取配置值
参数:
- auth (AuthSchema): 认证信息模型
- config_key (str): 配置管理型key
返回:
- str | None: 配置值字符串或None
"""
obj = await ParamsCRUD(auth).get_obj_by_key_crud(key=config_key)
if not obj:
raise CustomException(msg=f'配置键 {config_key} 不存在')
return obj.config_value
@classmethod
async def get_obj_list_service(cls, auth: AuthSchema, search: ParamsQueryParam | None = None, order_by: list[dict] | None = None) -> list[dict]:
"""
获取配置管理型列表
参数:
- auth (AuthSchema): 认证信息模型
- search (ParamsQueryParam | None): 查询参数对象
- order_by (list[dict] | None): 排序参数列表
返回:
- list[dict]: 配置管理型模型实例字典列表表示
"""
obj_list = None
if search:
obj_list = await ParamsCRUD(auth).get_obj_list_crud(search=search.__dict__, order_by=order_by)
else:
obj_list = await ParamsCRUD(auth).get_obj_list_crud()
return [ParamsOutSchema.model_validate(obj).model_dump() for obj in obj_list]
@classmethod
async def create_obj_service(cls, auth: AuthSchema, redis: Redis, data: ParamsCreateSchema) -> dict:
"""
创建配置管理型
参数:
- auth (AuthSchema): 认证信息模型
- redis (Redis): Redis 客户端实例
- data (ParamsCreateSchema): 配置管理型创建模型
返回:
- dict: 新创建的配置管理型模型实例字典表示
"""
exist_obj = await ParamsCRUD(auth).get(config_key=data.config_key)
if exist_obj:
raise CustomException(msg='创建失败该配置key已存在')
obj = await ParamsCRUD(auth).create_obj_crud(data=data)
new_obj_dict = ParamsOutSchema.model_validate(obj).model_dump()
# 同步redis
redis_key = f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:{data.config_key}"
try:
result = await RedisCURD(redis).set(
key=redis_key,
value="",
)
if not result:
log.error(f"同步配置到缓存失败: {new_obj_dict}")
raise CustomException(msg="同步配置到缓存失败")
except Exception as e:
log.error(f"创建字典类型失败: {e}")
raise CustomException(msg=f"创建字典类型失败 {e}")
return new_obj_dict
@classmethod
async def update_obj_service(cls, auth: AuthSchema, redis: Redis, id:int, data: ParamsUpdateSchema) -> dict:
"""
更新配置管理型
参数:
- auth (AuthSchema): 认证信息模型
- redis (Redis): Redis 客户端实例
- id (int): 配置管理型ID
- data (ParamsUpdateSchema): 配置管理型更新模型
返回:
- Dict: 更新后的配置管理型模型实例字典表示
"""
exist_obj = await ParamsCRUD(auth).get_obj_by_id_crud(id=id)
if not exist_obj:
raise CustomException(msg='更新失败,该数系统配置不存在')
if exist_obj.config_key != data.config_key:
raise CustomException(msg='更新失败系统配置key不允许修改')
new_obj = await ParamsCRUD(auth).update_obj_crud(id=id, data=data)
if not new_obj:
raise CustomException(msg='更新失败,系统配置不存在')
new_obj_dict = ParamsOutSchema.model_validate(new_obj).model_dump()
# 同步redis
redis_key = f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:{new_obj.config_key}"
try:
value = json.dumps(new_obj_dict, ensure_ascii=False)
result = await RedisCURD(redis).set(
key=redis_key,
value=value,
)
if not result:
log.error(f"同步配置到缓存失败: {new_obj_dict}")
raise CustomException(msg="同步配置到缓存失败")
except Exception as e:
log.error(f"更新系统配置失败: {e}")
raise CustomException(msg="更新系统配置失败")
return new_obj_dict
@classmethod
async def delete_obj_service(cls, auth: AuthSchema, redis: Redis, ids: list[int]) -> None:
"""
删除配置管理型
参数:
- auth (AuthSchema): 认证信息模型
- redis (Redis): Redis 客户端实例
- ids (list[int]): 配置管理型ID列表
返回:
- None
"""
if len(ids) < 1:
raise CustomException(msg='删除失败,删除对象不能为空')
for id in ids:
exist_obj = await ParamsCRUD(auth).get_obj_by_id_crud(id=id)
if not exist_obj:
raise CustomException(msg='删除失败,该数据字典类型不存在')
# 检查是否是否初始化类型
if exist_obj.config_type:
# 如果有字典数据,不能删除
raise CustomException(msg=f'{exist_obj.config_name} 删除失败,系统初始化配置不可以删除')
await ParamsCRUD(auth).delete_obj_crud(ids=ids)
# 同步删除Redis缓存
for id in ids:
exist_obj = await ParamsCRUD(auth).get_obj_by_id_crud(id=id)
if not exist_obj:
continue
redis_key = f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:{exist_obj.config_key}"
try:
await RedisCURD(redis).delete(redis_key)
log.info(f"删除系统配置成功: {id}")
except Exception as e:
log.error(f"删除系统配置失败: {e}")
raise CustomException(msg="删除字典类型失败")
@classmethod
async def export_obj_service(cls, data_list: list[dict]) -> bytes:
"""
导出系统配置列表
参数:
- data_list (list[dict]): 系统配置模型实例字典列表表示
返回:
- bytes: Excel文件二进制数据
"""
mapping_dict = {
'id': '编号',
'config_name': '参数名称',
'config_key': '参数键名',
'config_value': '参数键值',
'config_type': '系统内置((True:是 False:否))',
'description': '备注',
'created_time': '创建时间',
'updated_time': '更新时间',
'created_id': '创建者ID',
'updated_id': '更新者ID',
}
# 复制数据并转换状态
data = data_list.copy()
for item in data:
# 处理状态
item['config_type'] = '' if item.get('config_type') else ''
item['creator'] = item.get('creator', {}).get('name', '未知') if isinstance(item.get('creator'), dict) else '未知'
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
@classmethod
async def upload_service(cls, file: UploadFile) -> dict:
"""
上传文件到OSS
参数:
- file (UploadFile): 上传的文件对象
返回:
- dict: 上传文件的响应模型实例字典表示
"""
# 使用OSS上传替代本地上传
oss_util = OSSUtil()
filename, oss_key, file_url = await oss_util.upload_file(file=file)
log.info(f"文件上传OSS成功: {filename}")
return UploadResponseSchema(
file_path=oss_key, # OSS对象键
file_name=filename, # 生成的文件名
origin_name=file.filename, # 原始文件名
file_url=file_url, # OSS访问URL
).model_dump()
@classmethod
async def init_config_service(cls, redis: Redis) -> None:
"""
初始化系统配置
参数:
- redis (Redis): Redis 客户端实例
返回:
- None
"""
async with async_db_session() as session:
async with session.begin():
# 在初始化过程中,不需要检查数据权限
auth = AuthSchema(db=session, check_data_scope=False)
config_obj = await ParamsCRUD(auth).get_obj_list_crud()
if not config_obj:
raise CustomException(msg="系统配置不存在")
try:
# 保存到Redis并设置过期时间
for config in config_obj:
redis_key = (f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:{config.config_key}")
config_obj_dict = ParamsOutSchema.model_validate(config).model_dump()
value = json.dumps(config_obj_dict, ensure_ascii=False)
result = await RedisCURD(redis).set(
key=redis_key,
value=value,
)
log.info(f"✅ 系统配置缓存成功: {config.config_key}")
if not result:
log.error(f"❌️ 初始化系统配置失败: {config_obj_dict}")
raise CustomException(msg="初始化系统配置失败")
except Exception as e:
log.error(f"❌️ 初始化系统配置失败: {e}")
raise CustomException(msg="初始化系统配置失败")
@classmethod
async def get_init_config_service(cls, redis: Redis) -> list[dict]:
"""
获取系统配置
参数:
- redis (Redis): Redis 客户端实例
返回:
- list[dict]: 系统配置模型实例字典列表表示
"""
redis_keys = await RedisCURD(redis).get_keys(f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:*")
redis_configs = await RedisCURD(redis).mget(redis_keys)
configs = []
for config in redis_configs:
if not config:
continue
try:
new_config = json.loads(config)
configs.append(new_config)
except Exception as e:
log.error(f"解析系统配置数据失败: {e}")
continue
return configs
@classmethod
async def get_system_config_for_middleware(cls, redis: Redis) -> dict:
"""
获取中间件所需的系统配置
参数:
- redis (Redis): Redis 客户端实例
返回:
- dict: 包含演示模式、IP白名单、API白名单和IP黑名单的配置字典
"""
# 定义需要获取的配置键
config_keys = [
f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:demo_enable",
f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:ip_white_list",
f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:white_api_list_path",
f"{RedisInitKeyConfig.SYSTEM_CONFIG.key}:ip_black_list"
]
# 批量获取配置
config_values = await RedisCURD(redis).mget(config_keys)
# 初始化默认配置
config_result = {
"demo_enable": False,
"ip_white_list": [],
"white_api_list_path": [],
"ip_black_list": []
}
# 解析演示模式配置
if config_values[0]:
try:
demo_config = json.loads(config_values[0])
config_result["demo_enable"] = demo_config.get("config_value", False) if isinstance(demo_config, dict) else False
except json.JSONDecodeError:
log.error(f"解析演示模式配置失败")
# 解析IP白名单配置
if config_values[1]:
try:
ip_white_config = json.loads(config_values[1])
# 确保是列表类型
config_result["ip_white_list"] = json.loads(ip_white_config.get("config_value", []))
except json.JSONDecodeError:
log.error(f"解析IP白名单配置失败")
# 解析IP黑名单
# 解析API路径白名单
if config_values[2]:
try:
white_api_config = json.loads(config_values[2])
# 确保是列表类型
config_result["white_api_list_path"] = json.loads(white_api_config.get("config_value", []))
except json.JSONDecodeError:
log.error(f"解析API白名单配置失败")
# 解析IP黑名单
if config_values[3]:
try:
black_ip_config = json.loads(config_values[3])
# 确保是列表类型
config_result["ip_black_list"] = json.loads(black_ip_config.get("config_value", []))
except json.JSONDecodeError:
log.error(f"解析IP黑名单配置失败")
return config_result