db.config   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Importance

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

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 configparser as cp
33
import logging
34
import os
35
36
FILENAME = 'config.ini'
37
FILE = os.path.join(os.path.expanduser("~"), '.oemof', FILENAME)
38
39
cfg = cp.RawConfigParser()
40
_loaded = False
41
42
43
def load_config(filename):
44
    """
45
    Load data from config file to `cfg` that can be accessed by get, set
46
    afterwards.
47
48
    Specify absolute or relative path to your config file.
49
50
    Parameters
51
    ----------
52
    filename : str
53
        Relative or absolute path
54
    """
55
56
    if filename is None:
57
        filename = ''
58
59
    abs_filename = os.path.join(os.getcwd(), filename)
60
61
    global FILE
62
63
    # find the config file
64
    if os.path.isfile(filename):
65
        FILE = filename
66
    elif os.path.isfile(abs_filename):
67
        FILE = abs_filename
68
    elif os.path.isfile(FILE):
69
        pass
70
    else:
71
        if os.path.dirname(filename):
72
            file_not_found = filename
73
        else:
74
            file_not_found = abs_filename
75
        file_not_found_message(file_not_found)
76
77
    # load config
78
    init(FILE)
79
80
81
def file_not_found_message(file_not_found):
82
    """
83
    Show error message incl. help if file not found
84
85
    Parameters
86
    ----------
87
    file_not_found : str
88
        Relative or absolute path
89
    """
90
91
    logging.error(
92
        """
93
        Config file {file} cannot be found.  Make sure this file exists!
94
95
        An exemplary section in the config file looks as follows
96
97
        [database]
98
        username = username under which to connect to the database
99
        database = name of the database from which to read
100
        host     = host to connect to
101
        port     = port to connect to
102
103
        For further advice, see in the docs (https://oemofdb.readthedocs.io)
104
        how to format the config.
105
        """.format(file=file_not_found))
106
107
108
def main():
109
    pass
110
111
112
def init(FILE):
113
    """
114
    Read config file
115
116
    Parameters
117
    ----------
118
    FILE : str
119
        Absolute path to config file (incl. filename)
120
121
    """
122
    cfg.read(FILE)
123
    global _loaded
124
    _loaded = True
125
126
127
def get(section, key):
128
    """
129
    returns the value of a given key of a given section of the main
130
    config file.
131
132
    Parameters
133
    ----------
134
    section : str
135
        the section.
136
    key : str
137
        the key.
138
139
    Returns
140
    -------
141
    float, int, bool, str
142
        The value which will be casted to float, int or boolean. If no cast is
143
        successful, the raw string will be returned.
144
145
    """
146
    # FILE = 'config_misc'
147
    if not _loaded:
148
        init(FILE)
149
    try:
150
        return cfg.getint(section, key)
151
    except ValueError:
152
        try:
153
            return cfg.getfloat(section, key)
154
        except ValueError:
155
            try:
156
                return cfg.getboolean(section, key)
157
            except ValueError:
158
                value = cfg.get(section, key)
159
                if value == "None":
160
                    value = None
161
                return value
162
163
164
def set(section, key, value):
165
    """
166
    sets a value to a [section] key - pair.
167
    if the section doesn't exist yet, it will be created.
168
169
    Parameters
170
    ----------
171
    section : str
172
        the section.
173
    key : str
174
        the key.
175
    value : float, int, str
176
        the value.
177
    """
178
179
    if not _loaded:
180
        init(FILE)
181
182
    if not cfg.has_section(section):
183
        cfg.add_section(section)
184
185
    cfg.set(section, key, value)
186
187
    with open(FILE, 'w') as configfile:
188
        cfg.write(configfile)
189