db_config.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import json
  2. import os
  3. from typing import Dict, Any
  4. from dotenv import load_dotenv, find_dotenv
  5. class DatabaseConfig:
  6. """数据库配置管理类"""
  7. def __init__(self, env_file: str = '.env'):
  8. self.env_file = env_file
  9. self._config = None
  10. def load_config(self) -> Dict[str, Any]:
  11. """从.env文件加载数据库配置"""
  12. if self._config is not None:
  13. return self._config
  14. # 使用 python-dotenv 加载环境变量
  15. # find_dotenv() 会自动查找 .env 文件
  16. env_path = find_dotenv(self.env_file)
  17. if not env_path:
  18. # 手动尝试多个可能的.env文件位置
  19. possible_paths = [
  20. # 当前工作目录
  21. os.path.join(os.getcwd(), self.env_file),
  22. # 项目根目录(从当前文件位置推算)
  23. os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), self.env_file),
  24. # mysql目录的上级目录的上级目录
  25. os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), self.env_file)
  26. ]
  27. for path in possible_paths:
  28. if os.path.exists(path):
  29. env_path = path
  30. break
  31. if not env_path:
  32. searched_paths = '\n'.join(possible_paths)
  33. raise FileNotFoundError(f"配置文件 {self.env_file} 不存在,已搜索以下路径:\n{searched_paths}")
  34. # 加载环境变量
  35. load_dotenv(env_path)
  36. # 从环境变量中读取 DB_INFO
  37. db_info_str = os.getenv('DB_INFO')
  38. if not db_info_str:
  39. raise ValueError("未找到DB_INFO配置")
  40. # 解析 JSON 格式的数据库配置
  41. try:
  42. self._config = json.loads(db_info_str)
  43. except json.JSONDecodeError as e:
  44. raise ValueError(f"DB_INFO配置格式错误: {e}")
  45. # 验证必要的配置项
  46. required_keys = ['host', 'database', 'user', 'passwd']
  47. for key in required_keys:
  48. if key not in self._config:
  49. raise ValueError(f"缺少必要的配置项: {key}")
  50. # 设置默认值
  51. self._config.setdefault('port', 3306)
  52. self._config.setdefault('charset', 'utf8')
  53. return self._config
  54. def get_connection_params(self) -> Dict[str, Any]:
  55. """获取数据库连接参数"""
  56. config = self.load_config()
  57. return {
  58. 'host': config['host'],
  59. 'port': config['port'],
  60. 'user': config['user'],
  61. 'password': config['passwd'],
  62. 'database': config['database'],
  63. 'charset': config['charset'],
  64. 'autocommit': False,
  65. 'cursorclass': None # 将在连接池中设置
  66. }
  67. # 全局配置实例
  68. db_config = DatabaseConfig()