Initial commit
This commit is contained in:
74
config_file.py
Normal file
74
config_file.py
Normal file
@@ -0,0 +1,74 @@
|
||||
import json
|
||||
import os
|
||||
import yaml
|
||||
|
||||
def read_config(name):
|
||||
if not os.path.isfile(name):
|
||||
raise Exception(f"File {name} doesn't exists")
|
||||
filename, ext = os.path.splitext(name)
|
||||
if 'json' in ext:
|
||||
return read_json(name)
|
||||
elif 'properties' in ext:
|
||||
return read_prop(name)
|
||||
elif 'yaml' in ext or 'yml' in ext:
|
||||
return read_yaml(name)
|
||||
else:
|
||||
raise Exception("Wrong file type")
|
||||
|
||||
def read_json(name):
|
||||
with open(name, 'r', encoding='utf-8') as f:
|
||||
j_conf = json.load(f)
|
||||
conf = {}
|
||||
for key, value in j_conf.items():
|
||||
conf[key] = value
|
||||
return conf
|
||||
|
||||
def read_prop(filepath, sep='=', comment_char='#'):
|
||||
"""
|
||||
Read the file passed as parameter as a properties file.
|
||||
"""
|
||||
conf = {}
|
||||
with open(filepath, "rt") as f:
|
||||
for line in f:
|
||||
l = line.strip()
|
||||
if l and not l.startswith(comment_char):
|
||||
key_value = l.split(sep)
|
||||
key = key_value[0].strip()
|
||||
value = sep.join(key_value[1:]).strip().strip('"')
|
||||
conf[key] = value
|
||||
return conf
|
||||
|
||||
def read_yaml(name, secrets_file='secrets.yaml'):
|
||||
# Load secrets first
|
||||
secrets = {}
|
||||
secrets_path = os.path.join(os.path.dirname(name), secrets_file)
|
||||
|
||||
if os.path.exists(secrets_path):
|
||||
with open(secrets_path, 'r', encoding='utf-8') as f:
|
||||
secrets = yaml.safe_load(f) or {}
|
||||
|
||||
# Define a custom constructor for !secret tag
|
||||
def secret_constructor(loader, node):
|
||||
secret_key = loader.construct_scalar(node)
|
||||
if secret_key not in secrets:
|
||||
raise ValueError(f"Secret '{secret_key}' not found in {secrets_file}")
|
||||
return secrets[secret_key]
|
||||
|
||||
# Register the custom constructor
|
||||
yaml.add_constructor('!secret', secret_constructor, Loader=yaml.SafeLoader)
|
||||
|
||||
# Load the main configuration
|
||||
conf = {}
|
||||
with open(name, 'r', encoding='utf-8') as f:
|
||||
y_conf = yaml.safe_load(f)
|
||||
if y_conf:
|
||||
for key, value in y_conf.items():
|
||||
conf[key] = value
|
||||
|
||||
return conf
|
||||
|
||||
def main():
|
||||
pass
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user