-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig_manager.py
More file actions
213 lines (180 loc) · 7.8 KB
/
config_manager.py
File metadata and controls
213 lines (180 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""
Configuration Management Module
Configuration Management Module
Responsible for reading and creating system configuration file config.json
"""
import json
import os
import sys
from pathlib import Path
from typing import Dict, Any
def get_executable_dir() -> Path:
"""
Get the directory where the executable file is located
This function handles both development environment and packaged executable scenarios:
- In development: returns the directory containing the script file
- In packaged executable: returns the directory containing the executable file
Returns:
Path: Directory path where the executable/script is located
"""
if getattr(sys, 'frozen', False):
# Running as packaged executable (PyInstaller, py2exe, etc.)
if hasattr(sys, '_MEIPASS'):
# PyInstaller case: sys.executable points to the executable file
return Path(sys.executable).parent
else:
# Other packaging tools
return Path(sys.executable).parent
else:
# Running as Python script in development environment
return Path(__file__).parent
class ConfigManager:
"""Configuration management class"""
def __init__(self, config_path: str = None):
"""
Initialize configuration manager
Args:
config_path: Configuration file path, if None, use config.json in the executable directory
"""
if config_path is None:
# Get executable directory
executable_dir = get_executable_dir()
self.config_path = executable_dir / "config.json"
else:
self.config_path = Path(config_path)
self.config = self._load_or_create_config()
def _get_default_config(self) -> Dict[str, Any]:
"""Get default configuration"""
# Get executable directory as default database path
executable_dir = get_executable_dir()
return {
"database": {
"path": str(executable_dir),
"filename": "profile_data.db"
},
"server": {
"port": 8088,
"host": "0.0.0.0"
},
"system": {
"timezone_offset": 8,
"privacy_level": "private"
}
}
def _load_or_create_config(self) -> Dict[str, Any]:
"""Load or create configuration file"""
try:
if self.config_path.exists():
# Read existing configuration file
with open(self.config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
# Check and supplement missing configuration items
default_config = self._get_default_config()
updated = False
# Check database configuration
if 'database' not in config:
config['database'] = default_config['database']
updated = True
else:
if 'path' not in config['database']:
config['database']['path'] = default_config['database']['path']
updated = True
if 'filename' not in config['database']:
config['database']['filename'] = default_config['database']['filename']
updated = True
# Check server configuration
if 'server' not in config:
config['server'] = default_config['server']
updated = True
else:
if 'port' not in config['server']:
config['server']['port'] = default_config['server']['port']
updated = True
if 'host' not in config['server']:
config['server']['host'] = default_config['server']['host']
updated = True
# Check system configuration
if 'system' not in config:
config['system'] = default_config['system']
updated = True
else:
if 'timezone_offset' not in config['system']:
config['system']['timezone_offset'] = default_config['system']['timezone_offset']
updated = True
if 'privacy_level' not in config['system']:
config['system']['privacy_level'] = default_config['system']['privacy_level']
updated = True
# If updated, save configuration file
if updated:
self._save_config(config)
return config
else:
# Create default configuration file
config = self._get_default_config()
self._save_config(config)
print(f"Default configuration file created: {self.config_path}")
return config
except Exception as e:
print(f"Configuration file processing error: {e}")
print("Using default configuration")
return self._get_default_config()
def _save_config(self, config: Dict[str, Any]):
"""Save configuration file"""
try:
# Ensure the directory exists
self.config_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.config_path, 'w', encoding='utf-8') as f:
json.dump(config, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"Failed to save configuration file: {e}")
def get_database_path(self) -> str:
"""Get complete database path"""
db_dir = Path(self.config['database']['path'])
db_filename = self.config['database']['filename']
return str(db_dir / db_filename)
def get_database_dir(self) -> str:
"""Get database directory path"""
return self.config['database']['path']
def get_server_port(self) -> int:
"""Get server port"""
return self.config['server']['port']
def get_server_host(self) -> str:
"""Get server host"""
return self.config['server']['host']
def get_timezone_offset(self) -> int:
"""Get timezone offset"""
return self.config['system']['timezone_offset']
def get_privacy_level(self) -> str:
"""Get privacy level"""
return self.config['system']['privacy_level']
def update_config(self, **kwargs):
"""Update configuration"""
try:
# Support nested updates
for key, value in kwargs.items():
if '.' in key:
# Support nested keys like database.path
keys = key.split('.')
current = self.config
for k in keys[:-1]:
if k not in current:
current[k] = {}
current = current[k]
current[keys[-1]] = value
else:
self.config[key] = value
self._save_config(self.config)
print("Configuration updated")
except Exception as e:
print(f"Failed to update configuration: {e}")
def get_config(self) -> Dict[str, Any]:
"""Get complete configuration"""
return self.config.copy()
# Global configuration manager instance
_config_manager = None
def get_config_manager() -> ConfigManager:
"""Get configuration manager instance (singleton pattern)"""
global _config_manager
if _config_manager is None:
_config_manager = ConfigManager()
return _config_manager