From 5ea8a93715817a375f5378bf9135474aa61d3d10 Mon Sep 17 00:00:00 2001 From: Miguel BarĂ£o Date: Sun, 5 Feb 2023 18:30:35 +0000 Subject: [PATCH] refactor main.py --- aprendizations/main.py | 77 +++++++++++++++++++++++++++++------------------------------------------------ 1 file changed, 29 insertions(+), 48 deletions(-) diff --git a/aprendizations/main.py b/aprendizations/main.py index 2f1bae1..92e3eca 100644 --- a/aprendizations/main.py +++ b/aprendizations/main.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 ''' -Setup configurations and then runs the application. +Setup and run the application. ''' @@ -13,12 +13,11 @@ import logging.config from os import environ, path import ssl import sys -from typing import Any, Dict +from typing import Dict # this project from .learnapp import LearnApp, LearnException from .serve import webserver -from .tools import load_yaml from . import APP_NAME, APP_VERSION @@ -28,67 +27,62 @@ def parse_cmdline_arguments(): Parses command line arguments. Uses the argparse package. ''' - argparser = argparse.ArgumentParser( + parser = argparse.ArgumentParser( description='Webserver for interactive learning and practice. ' 'Please read the documentation included with this software before ' 'using it.' ) - argparser.add_argument( + parser.add_argument( 'courses', type=str, nargs='?', default='courses.yaml', help='configuration file in YAML format.' ) - argparser.add_argument( + parser.add_argument( '-v', '--version', action='store_true', help='show version information and exit' ) - argparser.add_argument( + parser.add_argument( '--prefix', type=str, default='.', help='path where the topic directories can be found (default: .)' ) - argparser.add_argument( + parser.add_argument( '--port', type=int, default=8443, help='port for the HTTPS server (default: 8443)' ) - argparser.add_argument( + parser.add_argument( '--db', type=str, default='students.db', help='SQLite3 database file (default: students.db)' ) - argparser.add_argument( + parser.add_argument( '-c', '--check', action='store_true', help='sanity check questions (can take awhile)' ) - argparser.add_argument( + parser.add_argument( '--debug', action='store_true', help='enable debug mode' ) - return argparser.parse_args() + return parser.parse_args() # ---------------------------------------------------------------------------- -def get_logger_config(debug: bool = False) -> Any: +def get_logger_config(debug: bool = False) -> Dict: ''' Loads logger configuration in yaml format from a file, otherwise sets up a default configuration. Returns the configuration. ''' - if debug: - filename, level = 'logger-debug.yaml', 'DEBUG' - else: - filename, level = 'logger.yaml', 'INFO' - - config_dir = environ.get('XDG_CONFIG_HOME', '~/.config/') - config_file = path.join(path.expanduser(config_dir), APP_NAME, filename) - - default_config: Dict[str, Any] = { + level = 'DEBUG' if debug else 'INFO' + modules = ['learnapp', 'main', 'models', 'questions', 'renderer_markdown', + 'serve', 'student', 'tools'] + return { 'version': 1, 'formatters': { 'standard': { @@ -105,21 +99,13 @@ def get_logger_config(debug: bool = False) -> Any: }, }, 'loggers': { - '': { # configuration for serve.py + f'{APP_NAME}.{module}': { 'handlers': ['default'], 'level': level, - }, - }, + 'propagate': False, + } for module in modules + } } - default_config['loggers'].update({ - APP_NAME+'.'+module: { - 'handlers': ['default'], - 'level': level, - 'propagate': False, - } for module in ['learnapp', 'models', 'factory', 'tools', 'serve', - 'questions', 'student', 'main']}) - - return load_yaml(config_file, default=default_config) # ---------------------------------------------------------------------------- @@ -133,19 +119,15 @@ def main(): if arg.version: print(f'{APP_NAME} {APP_VERSION}\nPython {sys.version}') - sys.exit(0) + return # --- Setup logging logger_config = get_logger_config(arg.debug) logging.config.dictConfig(logger_config) - try: - logging.config.dictConfig(logger_config) - except (ValueError, TypeError, AttributeError, ImportError) as exc: - print('An error ocurred while setting up the logging system: %s', exc) - sys.exit(1) - - logging.info('====================== Start Logging ======================') + # setup logger for this module + logger = logging.getLogger(__name__) + logger.info('====================== Start Logging ======================') # --- get SSL certificates if 'XDG_DATA_HOME' in environ: @@ -158,7 +140,7 @@ def main(): ssl_ctx.load_cert_chain(path.join(certs_dir, 'cert.pem'), path.join(certs_dir, 'privkey.pem')) except FileNotFoundError: - logging.critical('SSL certificates missing in %s', certs_dir) + logger.critical('SSL certificates missing in %s', certs_dir) print('--------------------------------------------------------------', 'Certificates should be issued by a certificate authority (CA),', 'such as https://letsencrypt.org. ', @@ -176,7 +158,7 @@ def main(): '--------------------------------------------------------------', sep='\n') sys.exit(1) - logging.info('SSL certificates loaded') + logger.info('SSL certificates loaded') # --- start application -------------------------------------------------- try: @@ -185,14 +167,13 @@ def main(): dbase=arg.db, check=arg.check) except LearnException: - logging.critical('Failed to start application') + logger.critical('Failed to start application') sys.exit(1) - logging.info('LearnApp started') + logger.info('LearnApp started') # --- run webserver forever ---------------------------------------------- asyncio.run(webserver(app=app, ssl=ssl_ctx, port=arg.port, debug=arg.debug)) - - logging.critical('Webserver stopped.') + logger.critical('Webserver stopped.') # ---------------------------------------------------------------------------- -- libgit2 0.21.2