system_config.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. description = Column(String(255), comment="配置描述")
  18. is_system = Column(SmallInteger, default=1, comment="是否为系统配置:1-是,0-否")
  19. is_editable = Column(SmallInteger, default=1, comment="是否可编辑:1-是,0-否")
  20. is_deleted = Column(SmallInteger, default=0, comment="是否删除:0-否,1-是")
  21. created_at = Column(DateTime, default=beijing_now, comment="创建时间")
  22. updated_at = Column(DateTime, default=beijing_now, onupdate=beijing_now, comment="更新时间")
  23. @staticmethod
  24. def get_config_value(config_key: str, default_value: Any = None) -> Any:
  25. """获取配置值"""
  26. try:
  27. db = next(get_db())
  28. config = db.query(SystemConfig).filter(
  29. SystemConfig.config_key == config_key,
  30. SystemConfig.is_deleted == 0
  31. ).first()
  32. if not config:
  33. return default_value
  34. # 根据类型转换值
  35. if config.config_type == 'int':
  36. return int(config.config_value)
  37. elif config.config_type == 'bool':
  38. return config.config_value.lower() in ('1', 'true', 'yes')
  39. elif config.config_type == 'json':
  40. return json.loads(config.config_value)
  41. else:
  42. return config.config_value
  43. except Exception as e:
  44. print(f"获取配置失败 {config_key}: {e}")
  45. return default_value
  46. finally:
  47. if 'db' in locals():
  48. db.close()
  49. @staticmethod
  50. def get_all_configs() -> Dict[str, Any]:
  51. """获取所有配置"""
  52. try:
  53. db = next(get_db())
  54. configs = db.query(SystemConfig).filter(
  55. SystemConfig.is_deleted == 0
  56. ).all()
  57. result = {}
  58. for config in configs:
  59. value = SystemConfig.get_config_value(config.config_key)
  60. result[config.config_key] = value
  61. return result
  62. except Exception as e:
  63. print(f"获取所有配置失败: {e}")
  64. return {}
  65. finally:
  66. if 'db' in locals():
  67. db.close()
  68. @staticmethod
  69. def set_config_value(config_key: str, value: Any, config_type: str = 'string', description: str = '') -> bool:
  70. """设置配置值"""
  71. try:
  72. db = next(get_db())
  73. # 查找现有配置
  74. config = db.query(SystemConfig).filter(
  75. SystemConfig.config_key == config_key,
  76. SystemConfig.is_deleted == 0
  77. ).first()
  78. # 转换值
  79. if config_type == 'bool':
  80. str_value = '1' if value else '0'
  81. elif config_type == 'json':
  82. str_value = json.dumps(value)
  83. else:
  84. str_value = str(value)
  85. if config:
  86. # 更新现有配置
  87. config.config_value = str_value
  88. config.config_type = config_type
  89. if description:
  90. config.description = description
  91. config.updated_at = beijing_now()
  92. else:
  93. # 创建新配置
  94. new_config = SystemConfig(
  95. config_key=config_key,
  96. config_value=str_value,
  97. config_type=config_type,
  98. description=description,
  99. is_system=0, # 用户设置的配置
  100. is_editable=1
  101. )
  102. db.add(new_config)
  103. db.commit()
  104. return True
  105. except Exception as e:
  106. print(f"设置配置失败 {config_key}: {e}")
  107. if 'db' in locals():
  108. db.rollback()
  109. return False
  110. finally:
  111. if 'db' in locals():
  112. db.close()