Coverage for osm_pla/config/config.py: 46%

39 statements  

« prev     ^ index     » next       coverage.py v6.4.1, created at 2024-06-29 08:27 +0000

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"""Global configuration managed by environment variables.""" 

17 

18import logging 

19import os 

20 

21import pkg_resources 

22import yaml 

23 

24logger = logging.getLogger(__name__) 

25 

26 

27class Config: 

28 def __init__(self, config_file: str = ''): 

29 self.conf = {} 

30 self._read_config_file(config_file) 

31 self._read_env() 

32 

33 def _read_config_file(self, config_file): 

34 if not config_file: 

35 path = 'pla.yaml' 

36 config_file = pkg_resources.resource_filename(__name__, path) 

37 with open(config_file) as f: 

38 self.conf = yaml.load(f) 

39 

40 def _read_env(self): 

41 for env in os.environ: 

42 if not env.startswith("OSMPLA_"): 

43 continue 

44 elements = env.lower().split("_") 

45 if len(elements) < 3: 

46 logger.warning( 

47 "Environment variable %s=%s does not comply with required format. Section and/or field missing.", 

48 env, os.getenv(env)) 

49 continue 

50 section = elements[1] 

51 field = '_'.join(elements[2:]) 

52 value = os.getenv(env) 

53 if section not in self.conf: 

54 self.conf[section] = {} 

55 self.conf[section][field] = value 

56 

57 def get(self, section, field=None): 

58 if not field: 

59 return self.conf[section] 

60 return self.conf[section][field] 

61 

62 def set(self, section, field, value): 

63 if section not in self.conf: 

64 self.conf[section] = {} 

65 self.conf[section][field] = value