Passed
Push — dev ( f6dceb...782bb6 )
by Uwe
01:13
created

db.config   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 58
dl 0
loc 190
rs 10
c 0
b 0
f 0
wmc 19

6 Functions

Rating   Name   Duplication   Size   Complexity  
A set() 0 25 4
A file_not_found_message() 0 25 1
B load_config() 0 36 6
B get() 0 35 6
A main() 0 2 1
A init() 0 13 1
1
# -*- coding: utf-8 -*-
2
"""
3
Created on Fri Sep  5 12:26:40 2014
4
5
:module-author: steffen
6
:filename: config.py
7
8
9
This module provides a highlevel layer for reading and writing config files.
10
There must be a file called "config.ini" in the root-folder of the project.
11
The file has to be of the following structure to be imported correctly.
12
13
# this is a comment \n
14
# the filestructure is like: \n
15
 \n
16
[netCDF] \n
17
RootFolder = c://netCDF \n
18
FilePrefix = cd2 \n
19
 \n
20
[mySQL] \n
21
host = localhost \n
22
user = guest \n
23
password = root \n
24
database = znes \n
25
 \n
26
[SectionName] \n
27
OptionName = value \n
28
Option2 = value2 \n
29
30
"""
31
32
import os
33
import logging
34
35
import configparser as cp
36
37
FILENAME = 'config.ini'
38
FILE = os.path.join(os.path.expanduser("~"), '.oemof', FILENAME)
39
40
cfg = cp.RawConfigParser()
41
_loaded = False
42
43
44
def load_config(filename):
45
    """
46
    Load data from config file to `cfg` that can be accessed by get, set
47
    afterwards.
48
49
    Specify absolute or relative path to your config file.
50
51
    Parameters
52
    ----------
53
    filename : str
54
        Relative or absolute path
55
    """
56
57
    if filename is None:
58
        filename = ''
59
60
    abs_filename = os.path.join(os.getcwd(), filename)
61
62
    global FILE
63
64
    # find the config file
65
    if os.path.isfile(filename):
66
        FILE = filename
67
    elif os.path.isfile(abs_filename):
68
        FILE = abs_filename
69
    elif os.path.isfile(FILE):
70
        pass
71
    else:
72
        if os.path.dirname(filename):
73
            file_not_found = filename
74
        else:
75
            file_not_found = abs_filename
76
        file_not_found_message(file_not_found)
77
78
    # load config
79
    init(FILE)
80
81
82
def file_not_found_message(file_not_found):
83
    """
84
    Show error message incl. help if file not found
85
86
    Parameters
87
    ----------
88
    file_not_found : str
89
        Relative or absolute path
90
    """
91
92
    logging.error(
93
        """
94
        Config file {file} cannot be found.  Make sure this file exists!
95
96
        An exemplary section in the config file looks as follows
97
98
        [database]
99
        username = username under which to connect to the database
100
        database = name of the database from which to read
101
        host     = host to connect to
102
        port     = port to connect to
103
104
        For further advice, see in the docs (https://oemofdb.readthedocs.io)
105
        how to format the config.
106
        """.format(file=file_not_found))
107
108
109
def main():
110
    pass
111
112
113
def init(FILE):
114
    """
115
    Read config file
116
117
    Parameters
118
    ----------
119
    FILE : str
120
        Absolute path to config file (incl. filename)
121
122
    """
123
    cfg.read(FILE)
124
    global _loaded
125
    _loaded = True
126
127
128
def get(section, key):
129
    """
130
    returns the value of a given key of a given section of the main
131
    config file.
132
133
    Parameters
134
    ----------
135
    section : str
136
        the section.
137
    key : str
138
        the key.
139
140
    Returns
141
    -------
142
    float, int, bool, str
143
        The value which will be casted to float, int or boolean. If no cast is
144
        successful, the raw string will be returned.
145
146
    """
147
    # FILE = 'config_misc'
148
    if not _loaded:
149
        init(FILE)
150
    try:
151
        return cfg.getint(section, key)
152
    except ValueError:
153
        try:
154
            return cfg.getfloat(section, key)
155
        except ValueError:
156
            try:
157
                return cfg.getboolean(section, key)
158
            except ValueError:
159
                value = cfg.get(section, key)
160
                if value == "None":
161
                    value = None
162
                return value
163
164
165
def set(section, key, value):
166
    """
167
    sets a value to a [section] key - pair.
168
    if the section doesn't exist yet, it will be created.
169
170
    Parameters
171
    ----------
172
    section : str
173
        the section.
174
    key : str
175
        the key.
176
    value : float, int, str
177
        the value.
178
    """
179
180
    if not _loaded:
181
        init(FILE)
182
183
    if not cfg.has_section(section):
184
        cfg.add_section(section)
185
186
    cfg.set(section, key, value)
187
188
    with open(FILE, 'w') as configfile:
189
        cfg.write(configfile)
190