ogcli: move configuration data into a different file

Move the configuration into its own file so it is easier to access
from multiple files.
master
Alejandro Sirgo Rica 2024-11-06 13:19:26 +01:00 committed by OpenGnSys Support Team
parent 10a3897f92
commit c4eb5d165a
3 changed files with 34 additions and 18 deletions

View File

@ -20,6 +20,7 @@ from cli.objects.center import OgCenter
from cli.objects.room import OgRoom
from cli.objects.folder import OgFolder
from cli.objects.session import OgSession
from cli.config import cfg
import argparse
import requests
import sys
@ -77,7 +78,7 @@ class OgREST():
class OgCLI():
def __init__(self, cfg):
def __init__(self):
self.rest = OgREST(cfg['ip'], cfg['port'], cfg['api_token'])
def list(self, args):

31
cli/config.py 100644
View File

@ -0,0 +1,31 @@
#!/usr/bin/env python3
# Copyright (C) 2020-2024 Soleta Networks <opengnsys@soleta.eu>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
import json
OG_CLI_CFG_PATH = "/opt/opengnsys/etc/ogcli.json"
def load_config():
data = None
try:
with open(OG_CLI_CFG_PATH, 'r') as json_file:
data = json.load(json_file)
except json.JSONDecodeError:
sys.exit(f'ERROR: Failed parse malformed JSON file {OG_CLI_CFG_PATH}')
except Exception as e:
sys.exit(f'ERROR: cannot open {OG_CLI_CFG_PATH}: {e}')
required_cfg_params = {'api_token', 'ip', 'port'}
difference_cfg_params = required_cfg_params - data.keys()
if len(difference_cfg_params) > 0:
sys.exit(f'Missing {difference_cfg_params} key in '
f'json config file')
return data
cfg = load_config()

18
ogcli
View File

@ -15,8 +15,6 @@ import argparse
import json
import sys
OG_CLI_CFG_PATH = "/opt/opengnsys/etc/ogcli.json"
def sigint_handler(signum, frame):
print("User has pressed ctrl-C, interrupting...")
sys.exit(1)
@ -25,22 +23,8 @@ class CLI():
def __init__(self):
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
signal.signal(signal.SIGINT, sigint_handler)
try:
with open(OG_CLI_CFG_PATH, 'r') as json_file:
self.cfg = json.load(json_file)
except json.JSONDecodeError:
sys.exit(f'ERROR: Failed parse malformed JSON file '
f'{OG_CLI_CFG_PATH}')
except:
sys.exit(f'ERROR: cannot open {OG_CLI_CFG_PATH}')
required_cfg_params = {'api_token', 'ip', 'port'}
difference_cfg_params = required_cfg_params - self.cfg.keys()
if len(difference_cfg_params) > 0:
sys.exit(f'Missing {difference_cfg_params} key in '
f'json config file')
self.ogcli = OgCLI(self.cfg)
self.ogcli = OgCLI()
parser = argparse.ArgumentParser(prog='ogcli')
parser.add_argument('command', help='Subcommand to run', nargs='?',