system_config.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. """
  2. 系统配置模型(纵表设计)
  3. """
  4. from sqlalchemy import Column, Integer, String, DateTime, SmallInteger, Text, Enum
  5. from sqlalchemy.orm import Session
  6. from app.database import Base, get_db
  7. from app.utils.timezone import beijing_now
  8. from typing import Dict, Any, Optional
  9. import json
  10. class SystemConfig(Base):
  11. """系统配置表(纵表设计)"""
  12. __tablename__ = "system_config"
  13. id = Column(Integer, primary_key=True, index=True, comment="主键ID")
  14. config_key = Column(String(100), nullable=False, index=True, comment="配置键名")
  15. config_value = Column(String(500), nullable=False, comment="配置值")
  16. config_type = Column(Enum('int', 'string', 'bool', 'json'), default='string', comment="配置值类型")
  17. app_name = Column(String(100), default='backend-admin', comment="所属应用:backend-admin、backend-client,多个用逗号拼接")
  18. description = Column(String(255), comment="配置描述")
  19. is_system = Column(SmallInteger, default=1, comment="是否为系统配置:1-是,0-否")
  20. is_editable = Column(SmallInteger, default=1, comment="是否可编辑:1-是,0-否")
  21. is_deleted = Column(SmallInteger, default=0, comment="是否删除:0-否,1-是")
  22. created_at = Column(DateTime, default=beijing_now, comment="创建时间")
  23. updated_at = Column(DateTime, default=beijing_now, onupdate=beijing_now, comment="更新时间")
  24. @staticmethod
  25. def get_config_value(config_key: str, default_value: Any = None) -> Any:
  26. """获取配置值"""
  27. try:
  28. db = next(get_db())
  29. config = db.query(SystemConfig).filter(
  30. SystemConfig.config_key == config_key,
  31. SystemConfig.is_deleted == 0
  32. ).first()
  33. if not config:
  34. return default_value
  35. # 根据类型转换值
  36. if config.config_type == 'int':
  37. return int(config.config_value)
  38. elif config.config_type == 'bool':
  39. return config.config_value.lower() in ('1', 'true', 'yes')
  40. elif config.config_type == 'json':
  41. return json.loads(config.config_value)
  42. else:
  43. return config.config_value
  44. except Exception as e:
  45. print(f"获取配置失败 {config_key}: {e}")
  46. return default_value
  47. finally:
  48. if 'db' in locals():
  49. db.close()
  50. @staticmethod
  51. def get_all_configs() -> Dict[str, Any]:
  52. """获取所有配置"""
  53. try:
  54. db = next(get_db())
  55. configs = db.query(SystemConfig).filter(
  56. SystemConfig.is_deleted == 0
  57. ).all()
  58. result = {}
  59. for config in configs:
  60. value = SystemConfig.get_config_value(config.config_key)
  61. result[config.config_key] = value
  62. return result
  63. except Exception as e:
  64. print(f"获取所有配置失败: {e}")
  65. return {}
  66. finally:
  67. if 'db' in locals():
  68. db.close()
  69. @staticmethod
  70. def set_config_value(config_key: str, value: Any, config_type: str = 'string', description: str = '') -> bool:
  71. """设置配置值"""
  72. try:
  73. db = next(get_db())
  74. # 查找现有配置
  75. config = db.query(SystemConfig).filter(
  76. SystemConfig.config_key == config_key,
  77. SystemConfig.is_deleted == 0
  78. ).first()
  79. # 转换值
  80. if config_type == 'bool':
  81. str_value = '1' if value else '0'
  82. elif config_type == 'json':
  83. str_value = json.dumps(value)
  84. else:
  85. str_value = str(value)
  86. if config:
  87. # 更新现有配置
  88. config.config_value = str_value
  89. config.config_type = config_type
  90. if description:
  91. config.description = description
  92. config.updated_at = beijing_now()
  93. else:
  94. # 创建新配置
  95. new_config = SystemConfig(
  96. config_key=config_key,
  97. config_value=str_value,
  98. config_type=config_type,
  99. description=description,
  100. is_system=0, # 用户设置的配置
  101. is_editable=1
  102. )
  103. db.add(new_config)
  104. db.commit()
  105. return True
  106. except Exception as e:
  107. print(f"设置配置失败 {config_key}: {e}")
  108. if 'db' in locals():
  109. db.rollback()
  110. return False
  111. finally:
  112. if 'db' in locals():
  113. db.close()