FileServer/config_file.py
2025-10-05 16:42:27 +03:00

71 lines
2.1 KiB
Python
Executable File

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), os.path.getmtime(name)
elif 'properties' in ext:
return read_prop(name), os.path.getmtime(name)
elif 'yaml' in ext or 'yml' in ext:
return read_yaml(name), os.path.getmtime(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='#'):
conf = {}
with open(filepath, "rt", encoding='utf-8') 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()