1 |
|
# -*- coding: utf-8 -*- |
2 |
|
# Copyright 2020 ArctosLabs Scandinavia AB |
3 |
|
# |
4 |
|
# Licensed under the Apache License, Version 2.0 (the "License"); |
5 |
|
# you may not use this file except in compliance with the License. |
6 |
|
# You may obtain a copy of the License at |
7 |
|
# |
8 |
|
# http://www.apache.org/licenses/LICENSE-2.0 |
9 |
|
# |
10 |
|
# Unless required by applicable law or agreed to in writing, software |
11 |
|
# distributed under the License is distributed on an "AS IS" BASIS, |
12 |
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
13 |
|
# implied. |
14 |
|
# See the License for the specific language governing permissions and |
15 |
|
# limitations under the License. |
16 |
1 |
"""Global configuration managed by environment variables.""" |
17 |
|
|
18 |
1 |
import logging |
19 |
1 |
import os |
20 |
|
|
21 |
1 |
import pkg_resources |
22 |
1 |
import yaml |
23 |
|
|
24 |
1 |
logger = logging.getLogger(__name__) |
25 |
|
|
26 |
|
|
27 |
1 |
class Config: |
28 |
1 |
def __init__(self, config_file: str = ""): |
29 |
1 |
self.conf = {} |
30 |
1 |
self._read_config_file(config_file) |
31 |
1 |
self._read_env() |
32 |
|
|
33 |
1 |
def _read_config_file(self, config_file): |
34 |
0 |
if not config_file: |
35 |
0 |
path = "pla.yaml" |
36 |
0 |
config_file = pkg_resources.resource_filename(__name__, path) |
37 |
0 |
with open(config_file) as f: |
38 |
0 |
self.conf = yaml.safe_load(f) |
39 |
|
|
40 |
1 |
def _read_env(self): |
41 |
1 |
for env in os.environ: |
42 |
1 |
if not env.startswith("OSMPLA_"): |
43 |
1 |
continue |
44 |
0 |
elements = env.lower().split("_") |
45 |
0 |
if len(elements) < 3: |
46 |
0 |
logger.warning( |
47 |
|
"Environment variable %s=%s does not comply with required format. Section and/or field missing.", |
48 |
|
env, |
49 |
|
os.getenv(env), |
50 |
|
) |
51 |
0 |
continue |
52 |
0 |
section = elements[1] |
53 |
0 |
field = "_".join(elements[2:]) |
54 |
0 |
value = os.getenv(env) |
55 |
0 |
if section not in self.conf: |
56 |
0 |
self.conf[section] = {} |
57 |
0 |
self.conf[section][field] = value |
58 |
|
|
59 |
1 |
def get(self, section, field=None): |
60 |
0 |
if not field: |
61 |
0 |
return self.conf[section] |
62 |
0 |
return self.conf[section][field] |
63 |
|
|
64 |
1 |
def set(self, section, field, value): |
65 |
0 |
if section not in self.conf: |
66 |
0 |
self.conf[section] = {} |
67 |
0 |
self.conf[section][field] = value |