VWED_server/packaging/config_tool/startup_loader.py
2025-09-09 10:41:27 +08:00

92 lines
2.9 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
启动配置加载器
在主程序启动前加载配置文件中的设置
"""
import os
import sys
import configparser
from pathlib import Path
def load_startup_config():
"""加载启动配置并设置环境变量"""
try:
# 获取配置文件路径
if getattr(sys, 'frozen', False):
# 在打包后的可执行文件中
app_dir = Path(sys.executable).parent
else:
# 在开发环境中
app_dir = Path(__file__).parent.parent.parent
config_file = app_dir / "config.ini"
if config_file.exists():
config = configparser.ConfigParser()
config.read(str(config_file), encoding='utf-8')
# 加载数据库配置
if 'database' in config:
db_config = config['database']
if 'username' in db_config:
os.environ['DB_USER'] = db_config['username']
if 'password' in db_config:
os.environ['DB_PASSWORD'] = db_config['password']
if 'host' in db_config:
os.environ['DB_HOST'] = db_config['host']
# 加载API配置
if 'api' in config:
api_config = config['api']
if 'tf_api_base_url' in api_config:
os.environ['TF_API_BASE_URL'] = api_config['tf_api_base_url']
print(f"配置已从 {config_file} 加载")
return True
else:
print(f"配置文件不存在: {config_file}")
return False
except Exception as e:
print(f"加载配置失败: {e}")
return False
def ensure_config_exists():
"""确保配置文件存在,如果不存在则创建默认配置"""
try:
if getattr(sys, 'frozen', False):
app_dir = Path(sys.executable).parent
else:
app_dir = Path(__file__).parent.parent.parent
config_file = app_dir / "config.ini"
if not config_file.exists():
config = configparser.ConfigParser()
# 默认数据库配置
config['database'] = {
'username': 'root',
'password': 'root',
'host': 'localhost'
}
# 默认API配置
config['api'] = {
'tf_api_base_url': 'http://111.231.146.230:4080/jeecg-boot'
}
with open(str(config_file), 'w', encoding='utf-8') as f:
config.write(f)
print(f"已创建默认配置文件: {config_file}")
except Exception as e:
print(f"创建默认配置失败: {e}")
if __name__ == "__main__":
ensure_config_exists()
load_startup_config()