Coverage for /var/devmt/py/utils4_1.5.0rc1/utils4/config.py: 100%

23 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-12 15:38 +0100

1# Changed. 

2# -*- coding: utf-8 -*- 

3""" 

4:Purpose: Small helper module designed to load a program's JSON-based 

5 config file. 

6 

7:Platform: Linux/Windows | Python 3.6+ 

8:Developer: J Berendt 

9:Email: support@s3dev.uk 

10 

11:Comments: n/a 

12 

13:Example: 

14 To load a program's JSON-based config file:: 

15 

16 >>> from utils4 import config 

17 

18 >>> cfg = config.loadconfig() 

19 >>> my_param = cfg['my_param'] 

20 

21""" 

22 

23import os 

24import sys 

25import json 

26from utils4.dict2obj import Dict2Obj 

27 

28 

29def loadconfig(filename: str='config.json', return_as_obj: bool=False): 

30 """Load a program's JSON config file and return it as a dict or object. 

31 

32 Args: 

33 filename (str, optional): File name or (preferably) the 

34 **explicit** full file path path of the JSON config file to 

35 be loaded. Defaults to 'config.json'. 

36 return_as_object (bool, optional): If True, the dictionary is 

37 converted into an object, where the dictionary key/values 

38 are object attribute/values. Defaults to False. 

39 

40 :Design: 

41 By default, this function will search the program's directory 

42 for a file named ``config.json``. If the config file lives 

43 somewhere else, or you're using an IDE to develop, the safest 

44 option is to **explicitly define the path to the config file**. 

45 

46 If a path is found in the passed parameter, this path is used, 

47 and the function does not have to try and work out where the 

48 config file lives. 

49 

50 The ``return_as_obj`` parameter tells the function to convert 

51 and return the JSON file into an object, rather than a 

52 dictionary. This enables you to access the values from object 

53 attributes, rather than from dictionary keys. See use option 2. 

54 

55 :Assumptions: 

56 * The config file is a JSON file. 

57 * The config file lives in the program directory. 

58 

59 :Examples: 

60 

61 Option 1: Return the config file as a **dict**:: 

62 

63 >>> from utils4 import config 

64 

65 >>> cfg = config.loadconfig() 

66 >>> my_param = cfg['my_param'] 

67 

68 

69 Option 2: Return the config file as an **object**:: 

70 

71 >>> from utils4 import config 

72 

73 >>> cfg = config.loadconfig(return_as_object=True) 

74 >>> my_param = cfg.my_param 

75 

76 """ 

77 # Filename only. 

78 if os.path.dirname(filename) == '': 

79 progdir = os.path.dirname(os.path.realpath(sys.argv[0])) 

80 path_base = progdir if sys.argv[0] != '' else os.getcwd() 

81 fullpath = os.path.join(path_base, filename) 

82 # Full path. 

83 else: 

84 fullpath = filename 

85 if _file_exists(fullpath=fullpath): 

86 if return_as_obj: 

87 to_return = Dict2Obj(source='json', filepath=fullpath) 

88 else: 

89 to_return = _fromjson(filepath=fullpath) 

90 return to_return 

91 

92def _file_exists(fullpath: str) -> bool: 

93 """Test if the requested config file exists. 

94 

95 Args: 

96 fullpath (str): Full path to the file being tested. 

97 

98 Raises: 

99 IOError: If the file does not exist. 

100 

101 Returns: 

102 bool: True of the file exists, otherwise False. 

103 

104 """ 

105 exists = os.path.exists(fullpath) 

106 if not exists: 

107 raise IOError(f'The config file ({fullpath}) could not be found.') 

108 return exists 

109 

110def _fromjson(filepath: str) -> dict: 

111 """Extract values from the JSON file. 

112 

113 Args: 

114 filepath (str): Full path to the file to be read. 

115 

116 Returns: 

117 dict: JSON file content as a dictionary. 

118 

119 """ 

120 with open(filepath, 'r', encoding='utf-8') as f: 

121 return json.load(f)