1
|
import os
|
2
|
|
3
|
import configparser
|
4
|
import logging
|
5
|
from injector import singleton
|
6
|
|
7
|
from src.constants import DEFAULT_CONNECTION_STRING, TEST_DATABASE_FILE, DEFAULT_SERVER_BASE_URL
|
8
|
from src.constants import LOG_FILE_LOCATION, LOG_FORMAT
|
9
|
from src.utils.logger import Logger
|
10
|
|
11
|
DATABASE_SECTION = "Database"
|
12
|
DATABASE_CONNECTION_STRING = "ConnectionString"
|
13
|
|
14
|
SERVER_SECTION = "Server"
|
15
|
SERVER_BASE_URL = "ServerBaseURL"
|
16
|
|
17
|
|
18
|
class Configuration:
|
19
|
"""
|
20
|
Configuration class servers for injecting current application
|
21
|
configuration all over the application
|
22
|
"""
|
23
|
|
24
|
def __init__(self):
|
25
|
"""
|
26
|
Constructor
|
27
|
It must initialize all variables to their default values
|
28
|
"""
|
29
|
self.connection_string = DEFAULT_CONNECTION_STRING
|
30
|
self.base_server_url = DEFAULT_SERVER_BASE_URL
|
31
|
|
32
|
|
33
|
def test_configuration():
|
34
|
conf = Configuration()
|
35
|
conf.connection_string = TEST_DATABASE_FILE
|
36
|
return conf
|
37
|
|
38
|
|
39
|
def test_configuration_binder(binder):
|
40
|
binder.bind(Configuration, to=test_configuration(), scope=singleton)
|
41
|
|
42
|
|
43
|
def configure_env_variable(binder):
|
44
|
"""
|
45
|
Load configuration file stored in X509_CONFIG environment variable.
|
46
|
If the file is not specified, use the default configuration
|
47
|
:param binder: injector configuration binder instance
|
48
|
:return: N/A
|
49
|
"""
|
50
|
# TODO check: log which configuration is going to be used
|
51
|
config_name = "X509_CONFIG"
|
52
|
Logger.info(f"Using configuration '{config_name}'")
|
53
|
config_file = os.environ.get(config_name)
|
54
|
app_configuration = Configuration()
|
55
|
# if configuration file is not specified use the default configuration
|
56
|
if config_file is not None and os.path.exists(config_file):
|
57
|
config = configparser.ConfigParser()
|
58
|
config.read(config_file)
|
59
|
|
60
|
if config[DATABASE_SECTION] is not None:
|
61
|
database_config = config[DATABASE_SECTION]
|
62
|
app_configuration.connection_string = database_config.get(DATABASE_CONNECTION_STRING,
|
63
|
DEFAULT_CONNECTION_STRING)
|
64
|
if config[SERVER_SECTION] is not None:
|
65
|
server_config = config[SERVER_SECTION]
|
66
|
app_configuration.base_server_url = server_config.get(SERVER_BASE_URL,
|
67
|
DEFAULT_SERVER_BASE_URL)
|
68
|
|
69
|
binder.bind(Configuration, to=app_configuration, scope=singleton)
|
70
|
|
71
|
|
72
|
def configure_logging():
|
73
|
logging.basicConfig(filename=LOG_FILE_LOCATION.shortest_relative_path(),
|
74
|
filemode='a+',
|
75
|
format=LOG_FORMAT,
|
76
|
level=logging.DEBUG)
|
77
|
|
78
|
# TODO check is 'valid'
|
79
|
log = logging.getLogger('werkzeug')
|
80
|
log.disabled = True
|