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

39 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2024-06-22 10:12 +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.safe_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, 

49 os.getenv(env), 

50 ) 

51 continue 

52 section = elements[1] 

53 field = "_".join(elements[2:]) 

54 value = os.getenv(env) 

55 if section not in self.conf: 

56 self.conf[section] = {} 

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

58 

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

60 if not field: 

61 return self.conf[section] 

62 return self.conf[section][field] 

63 

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

65 if section not in self.conf: 

66 self.conf[section] = {} 

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