config.py
1.07 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
import os
import configparser
_config = None
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
CONFIG_PATH = os.path.join(BASE_DIR, 'config.ini')
DOT_ENV_PATH = os.path.join(BASE_DIR, '.env')
def _load_dot_env():
if not os.path.exists(DOT_ENV_PATH):
return
with open(DOT_ENV_PATH, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if '=' not in line:
continue
key, _, value = line.partition('=')
key = key.strip()
value = value.strip().strip('"').strip("'")
if key and key not in os.environ:
os.environ[key] = value
def get_config():
global _config
if _config is None:
_load_dot_env()
_config = configparser.ConfigParser()
_config.read(CONFIG_PATH, encoding='utf-8')
return _config
def get_env(key, default=None):
return os.environ.get(key, default)
def get_project_root():
return BASE_DIR