Commit 5ea8a93715817a375f5378bf9135474aa61d3d10

Authored by Miguel Barão
1 parent 36175c2c
Exists in dev

refactor main.py

Showing 1 changed file with 29 additions and 48 deletions   Show diff stats
aprendizations/main.py
1 1 #!/usr/bin/env python3
2 2  
3 3 '''
4   -Setup configurations and then runs the application.
  4 +Setup and run the application.
5 5 '''
6 6  
7 7  
... ... @@ -13,12 +13,11 @@ import logging.config
13 13 from os import environ, path
14 14 import ssl
15 15 import sys
16   -from typing import Any, Dict
  16 +from typing import Dict
17 17  
18 18 # this project
19 19 from .learnapp import LearnApp, LearnException
20 20 from .serve import webserver
21   -from .tools import load_yaml
22 21 from . import APP_NAME, APP_VERSION
23 22  
24 23  
... ... @@ -28,67 +27,62 @@ def parse_cmdline_arguments():
28 27 Parses command line arguments. Uses the argparse package.
29 28 '''
30 29  
31   - argparser = argparse.ArgumentParser(
  30 + parser = argparse.ArgumentParser(
32 31 description='Webserver for interactive learning and practice. '
33 32 'Please read the documentation included with this software before '
34 33 'using it.'
35 34 )
36 35  
37   - argparser.add_argument(
  36 + parser.add_argument(
38 37 'courses', type=str, nargs='?', default='courses.yaml',
39 38 help='configuration file in YAML format.'
40 39 )
41 40  
42   - argparser.add_argument(
  41 + parser.add_argument(
43 42 '-v', '--version', action='store_true',
44 43 help='show version information and exit'
45 44 )
46 45  
47   - argparser.add_argument(
  46 + parser.add_argument(
48 47 '--prefix', type=str, default='.',
49 48 help='path where the topic directories can be found (default: .)'
50 49 )
51 50  
52   - argparser.add_argument(
  51 + parser.add_argument(
53 52 '--port', type=int, default=8443,
54 53 help='port for the HTTPS server (default: 8443)'
55 54 )
56 55  
57   - argparser.add_argument(
  56 + parser.add_argument(
58 57 '--db', type=str, default='students.db',
59 58 help='SQLite3 database file (default: students.db)'
60 59 )
61 60  
62   - argparser.add_argument(
  61 + parser.add_argument(
63 62 '-c', '--check', action='store_true',
64 63 help='sanity check questions (can take awhile)'
65 64 )
66 65  
67   - argparser.add_argument(
  66 + parser.add_argument(
68 67 '--debug', action='store_true',
69 68 help='enable debug mode'
70 69 )
71 70  
72   - return argparser.parse_args()
  71 + return parser.parse_args()
73 72  
74 73  
75 74 # ----------------------------------------------------------------------------
76   -def get_logger_config(debug: bool = False) -> Any:
  75 +def get_logger_config(debug: bool = False) -> Dict:
77 76 '''
78 77 Loads logger configuration in yaml format from a file, otherwise sets up a
79 78 default configuration.
80 79 Returns the configuration.
81 80 '''
82 81  
83   - if debug:
84   - filename, level = 'logger-debug.yaml', 'DEBUG'
85   - else:
86   - filename, level = 'logger.yaml', 'INFO'
87   -
88   - config_dir = environ.get('XDG_CONFIG_HOME', '~/.config/')
89   - config_file = path.join(path.expanduser(config_dir), APP_NAME, filename)
90   -
91   - default_config: Dict[str, Any] = {
  82 + level = 'DEBUG' if debug else 'INFO'
  83 + modules = ['learnapp', 'main', 'models', 'questions', 'renderer_markdown',
  84 + 'serve', 'student', 'tools']
  85 + return {
92 86 'version': 1,
93 87 'formatters': {
94 88 'standard': {
... ... @@ -105,21 +99,13 @@ def get_logger_config(debug: bool = False) -> Any:
105 99 },
106 100 },
107 101 'loggers': {
108   - '': { # configuration for serve.py
  102 + f'{APP_NAME}.{module}': {
109 103 'handlers': ['default'],
110 104 'level': level,
111   - },
112   - },
  105 + 'propagate': False,
  106 + } for module in modules
  107 + }
113 108 }
114   - default_config['loggers'].update({
115   - APP_NAME+'.'+module: {
116   - 'handlers': ['default'],
117   - 'level': level,
118   - 'propagate': False,
119   - } for module in ['learnapp', 'models', 'factory', 'tools', 'serve',
120   - 'questions', 'student', 'main']})
121   -
122   - return load_yaml(config_file, default=default_config)
123 109  
124 110  
125 111 # ----------------------------------------------------------------------------
... ... @@ -133,19 +119,15 @@ def main():
133 119  
134 120 if arg.version:
135 121 print(f'{APP_NAME} {APP_VERSION}\nPython {sys.version}')
136   - sys.exit(0)
  122 + return
137 123  
138 124 # --- Setup logging
139 125 logger_config = get_logger_config(arg.debug)
140 126 logging.config.dictConfig(logger_config)
141 127  
142   - try:
143   - logging.config.dictConfig(logger_config)
144   - except (ValueError, TypeError, AttributeError, ImportError) as exc:
145   - print('An error ocurred while setting up the logging system: %s', exc)
146   - sys.exit(1)
147   -
148   - logging.info('====================== Start Logging ======================')
  128 + # setup logger for this module
  129 + logger = logging.getLogger(__name__)
  130 + logger.info('====================== Start Logging ======================')
149 131  
150 132 # --- get SSL certificates
151 133 if 'XDG_DATA_HOME' in environ:
... ... @@ -158,7 +140,7 @@ def main():
158 140 ssl_ctx.load_cert_chain(path.join(certs_dir, 'cert.pem'),
159 141 path.join(certs_dir, 'privkey.pem'))
160 142 except FileNotFoundError:
161   - logging.critical('SSL certificates missing in %s', certs_dir)
  143 + logger.critical('SSL certificates missing in %s', certs_dir)
162 144 print('--------------------------------------------------------------',
163 145 'Certificates should be issued by a certificate authority (CA),',
164 146 'such as https://letsencrypt.org. ',
... ... @@ -176,7 +158,7 @@ def main():
176 158 '--------------------------------------------------------------',
177 159 sep='\n')
178 160 sys.exit(1)
179   - logging.info('SSL certificates loaded')
  161 + logger.info('SSL certificates loaded')
180 162  
181 163 # --- start application --------------------------------------------------
182 164 try:
... ... @@ -185,14 +167,13 @@ def main():
185 167 dbase=arg.db,
186 168 check=arg.check)
187 169 except LearnException:
188   - logging.critical('Failed to start application')
  170 + logger.critical('Failed to start application')
189 171 sys.exit(1)
190   - logging.info('LearnApp started')
  172 + logger.info('LearnApp started')
191 173  
192 174 # --- run webserver forever ----------------------------------------------
193 175 asyncio.run(webserver(app=app, ssl=ssl_ctx, port=arg.port, debug=arg.debug))
194   -
195   - logging.critical('Webserver stopped.')
  176 + logger.critical('Webserver stopped.')
196 177  
197 178  
198 179 # ----------------------------------------------------------------------------
... ...