Projekt

Obecné

Profil

Stáhnout (2.44 KB) Statistiky
| Větev: | Tag: | Revize:
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

    
10
DATABASE_SECTION = "Database"
11
DATABASE_CONNECTION_STRING = "ConnectionString"
12

    
13
SERVER_SECTION = "Server"
14
SERVER_BASE_URL = "ServerBaseURL"
15

    
16

    
17
class Configuration:
18
    """
19
    Configuration class servers for injecting current application
20
    configuration all over the application
21
    """
22

    
23
    def __init__(self):
24
        """
25
        Constructor
26
        It must initialize all variables to their default values
27
        """
28
        self.connection_string = DEFAULT_CONNECTION_STRING
29
        self.base_server_url = DEFAULT_SERVER_BASE_URL
30

    
31

    
32
def test_configuration():
33
    conf = Configuration()
34
    conf.connection_string = TEST_DATABASE_FILE
35
    return conf
36

    
37

    
38
def test_configuration_binder(binder):
39
    binder.bind(Configuration, to=test_configuration(), scope=singleton)
40

    
41

    
42
def configure_env_variable(binder):
43
    """
44
    Load configuration file stored in X509_CONFIG environment variable.
45
    If the file is not specified, use the default configuration
46
    :param binder: injector configuration binder instance
47
    :return: N/A
48
    """
49
    # TODO log which configuration is going to be used
50
    config_file = os.environ.get("X509_CONFIG")
51
    app_configuration = Configuration()
52
    # if configuration file is not specified use the default configuration
53
    if config_file is not None and os.path.exists(config_file):
54
        config = configparser.ConfigParser()
55
        config.read(config_file)
56

    
57
        if config[DATABASE_SECTION] is not None:
58
            database_config = config[DATABASE_SECTION]
59
            app_configuration.connection_string = database_config.get(DATABASE_CONNECTION_STRING,
60
                                                                      DEFAULT_CONNECTION_STRING)
61
        if config[SERVER_SECTION] is not None:
62
            server_config = config[SERVER_SECTION]
63
            app_configuration.base_server_url = server_config.get(SERVER_BASE_URL,
64
                                                                  DEFAULT_SERVER_BASE_URL)
65

    
66
    binder.bind(Configuration, to=app_configuration, scope=singleton)
67

    
68

    
69
def configure_logging():
70
    logging.basicConfig(filename=LOG_FILE_LOCATION.shortest_relative_path(),
71
                        filemode='a+',
72
                        format=LOG_FORMAT,
73
                        level=logging.DEBUG)
(2-2/3)