1
|
import os
|
2
|
|
3
|
import configparser
|
4
|
import logging
|
5
|
|
6
|
from injector import singleton
|
7
|
|
8
|
from src.constants import DEFAULT_CONNECTION_STRING, TEST_DATABASE_FILE, DEFAULT_SERVER_BASE_URL, \
|
9
|
DEFAULT_LOG_LEVEL, DEFAULT_ROOT_DIR
|
10
|
|
11
|
DATABASE_SECTION = "Database"
|
12
|
DATABASE_CONNECTION_STRING = "ConnectionString"
|
13
|
|
14
|
SERVER_SECTION = "Server"
|
15
|
SERVER_BASE_URL = "ServerBaseURL"
|
16
|
SERVER_LOG_LEVEL = "LogLevel"
|
17
|
SERVER_ROOT_DIR = "RootDir"
|
18
|
|
19
|
LOG_LEVEL_MAPPING = {
|
20
|
"DEBUG": logging.DEBUG,
|
21
|
"INFO": logging.INFO,
|
22
|
"WARNING": logging.WARNING,
|
23
|
"ERROR": logging.ERROR,
|
24
|
"CRITICAL": logging.CRITICAL
|
25
|
}
|
26
|
|
27
|
|
28
|
class Configuration:
|
29
|
"""
|
30
|
Configuration class servers for injecting current application
|
31
|
configuration all over the application
|
32
|
"""
|
33
|
|
34
|
def __init__(self):
|
35
|
"""
|
36
|
Constructor
|
37
|
It must initialize all variables to their default values
|
38
|
"""
|
39
|
self.config_file = None
|
40
|
self.connection_string = DEFAULT_CONNECTION_STRING
|
41
|
self.base_server_url = DEFAULT_SERVER_BASE_URL
|
42
|
self.log_level = DEFAULT_LOG_LEVEL
|
43
|
self.root_dir = DEFAULT_ROOT_DIR
|
44
|
|
45
|
|
46
|
def test_configuration():
|
47
|
conf = Configuration()
|
48
|
conf.connection_string = TEST_DATABASE_FILE
|
49
|
return conf
|
50
|
|
51
|
|
52
|
def test_configuration_binder(binder):
|
53
|
binder.bind(Configuration, to=test_configuration(), scope=singleton)
|
54
|
|
55
|
|
56
|
def configure_env_variable(binder):
|
57
|
"""
|
58
|
Load configuration file stored in X509_CONFIG environment variable.
|
59
|
If the file is not specified, use the default configuration
|
60
|
:param binder: injector configuration binder instance
|
61
|
:return: N/A
|
62
|
"""
|
63
|
config_name = "X509_CONFIG"
|
64
|
config_file = os.environ.get(config_name)
|
65
|
app_configuration = Configuration()
|
66
|
# if configuration file is not specified use the default configuration
|
67
|
if config_file is not None and os.path.exists(config_file):
|
68
|
app_configuration.config_file = config_file
|
69
|
config = configparser.ConfigParser()
|
70
|
config.read(config_file)
|
71
|
|
72
|
if config[DATABASE_SECTION] is not None:
|
73
|
database_config = config[DATABASE_SECTION]
|
74
|
app_configuration.connection_string = database_config.get(DATABASE_CONNECTION_STRING,
|
75
|
DEFAULT_CONNECTION_STRING)
|
76
|
if config[SERVER_SECTION] is not None:
|
77
|
server_config = config[SERVER_SECTION]
|
78
|
app_configuration.base_server_url = server_config.get(SERVER_BASE_URL,
|
79
|
DEFAULT_SERVER_BASE_URL)
|
80
|
app_configuration.log_level = server_config.get(SERVER_LOG_LEVEL, DEFAULT_LOG_LEVEL)
|
81
|
app_configuration.root_dir = server_config.get(SERVER_ROOT_DIR, DEFAULT_ROOT_DIR)
|
82
|
|
83
|
binder.bind(Configuration, to=app_configuration, scope=singleton)
|