1
|
import os
|
2
|
|
3
|
import configparser
|
4
|
from injector import singleton
|
5
|
|
6
|
from src.constants import DEFAULT_CONNECTION_STRING, TEST_DATABASE_FILE, DEFAULT_SERVER_BASE_URL
|
7
|
|
8
|
DATABASE_SECTION = "Database"
|
9
|
DATABASE_CONNECTION_STRING = "ConnectionString"
|
10
|
|
11
|
SERVER_SECTION = "Server"
|
12
|
SERVER_BASE_URL = "ServerBaseURL"
|
13
|
|
14
|
|
15
|
class Configuration:
|
16
|
"""
|
17
|
Configuration class servers for injecting current application
|
18
|
configuration all over the application
|
19
|
"""
|
20
|
|
21
|
def __init__(self):
|
22
|
"""
|
23
|
Constructor
|
24
|
It must initialize all variables to their default values
|
25
|
"""
|
26
|
self.connection_string = DEFAULT_CONNECTION_STRING
|
27
|
self.base_server_url = DEFAULT_SERVER_BASE_URL
|
28
|
|
29
|
|
30
|
def test_configuration():
|
31
|
conf = Configuration()
|
32
|
conf.connection_string = TEST_DATABASE_FILE
|
33
|
return conf
|
34
|
|
35
|
|
36
|
def test_configuration_binder(binder):
|
37
|
binder.bind(Configuration, to=test_configuration(), scope=singleton)
|
38
|
|
39
|
|
40
|
def configure_env_variable(binder):
|
41
|
"""
|
42
|
Load configuration file stored in X509_CONFIG environment variable.
|
43
|
If the file is not specified, use the default configuration
|
44
|
:param binder: injector configuration binder instance
|
45
|
:return: N/A
|
46
|
"""
|
47
|
# TODO log which configuration is going to be used
|
48
|
config_file = os.environ.get("X509_CONFIG")
|
49
|
app_configuration = Configuration()
|
50
|
# if configuration file is not specified use the default configuration
|
51
|
if config_file is not None and os.path.exists(config_file):
|
52
|
config = configparser.ConfigParser()
|
53
|
config.read(config_file)
|
54
|
|
55
|
if config[DATABASE_SECTION] is not None:
|
56
|
database_config = config[DATABASE_SECTION]
|
57
|
app_configuration.connection_string = database_config.get(DATABASE_CONNECTION_STRING,
|
58
|
DEFAULT_CONNECTION_STRING)
|
59
|
if config[SERVER_SECTION] is not None:
|
60
|
server_config = config[SERVER_SECTION]
|
61
|
app_configuration.base_server_url = server_config.get(SERVER_BASE_URL,
|
62
|
DEFAULT_SERVER_BASE_URL)
|
63
|
|
64
|
binder.bind(Configuration, to=app_configuration, scope=singleton)
|