""" 服务器配置 """ import json import os import sys def _resolve_path(rel_path): """解析路径:打包后相对于可执行文件,开发时相对于脚本目录""" if getattr(sys, 'frozen', False): base = os.path.dirname(sys.executable) else: base = os.path.dirname(os.path.abspath(__file__)) return os.path.normpath(os.path.join(base, rel_path)) class Config: def __init__(self, config_file='config.json'): self.config_file = _resolve_path(config_file) # 数据库路径:开发环境在项目根目录,打包后在 exe 同级 if getattr(sys, 'frozen', False): db_path = _resolve_path('database/chat.db') else: db_path = _resolve_path('../database/chat.db') self.config = { 'host': '0.0.0.0', 'port': 8888, 'database': db_path, } self._load() def _load(self): if os.path.exists(self.config_file): try: with open(self.config_file, 'r') as f: self.config.update(json.load(f)) except Exception: pass def get(self, key, default=None): return self.config.get(key, default) config = Config()