diff options
Diffstat (limited to 'gn_auth/__init__.py')
| -rw-r--r-- | gn_auth/__init__.py | 55 |
1 files changed, 47 insertions, 8 deletions
diff --git a/gn_auth/__init__.py b/gn_auth/__init__.py index 6e2a884..d03c9ef 100644 --- a/gn_auth/__init__.py +++ b/gn_auth/__init__.py @@ -1,6 +1,8 @@ """Application initialisation module.""" import os import sys +import logging +import warnings from pathlib import Path from typing import Optional, Callable @@ -17,15 +19,22 @@ from gn_auth.auth.authentication.oauth2.server import setup_oauth2_server from . import settings from .errors import register_error_handlers +## Configure warnings: ## +# https://docs.python.org/3/library/warnings.html#the-warnings-filter +# filters form: (action, message, category, module, lineno) +warnings.filterwarnings(action="always", category=DeprecationWarning) + + class ConfigurationError(Exception): """Raised in case of a configuration error.""" + def check_mandatory_settings(app: Flask) -> None: """Verify that mandatory settings are defined in the application""" undefined = tuple( setting for setting in ( "SECRET_KEY", "SQL_URI", "AUTH_DB", "AUTH_MIGRATIONS", - "OAUTH2_SCOPE") + "OAUTH2_SCOPES_SUPPORTED") if not ((setting in app.config) and bool(app.config[setting]))) if len(undefined) > 0: raise ConfigurationError( @@ -52,27 +61,57 @@ def load_secrets_conf(app: Flask) -> None: app.config.from_pyfile(secretsfile) -def create_app( - config: Optional[dict] = None, - setup_logging: Callable[[Flask], None] = lambda appl: None -) -> Flask: +def dev_loggers(appl: Flask) -> logging.Logger: + """Setup the logging handlers.""" + stderr_handler = logging.StreamHandler(stream=sys.stderr) + appl.logger.addHandler(stderr_handler) + appl.logger.setLevel(appl.config["LOGLEVEL"]) + + return appl.logger + + +def gunicorn_loggers(appl: Flask) -> logging.Logger: + """Use gunicorn logging handlers for the application.""" + logger = logging.getLogger("gunicorn.error") + appl.logger.handlers = logger.handlers + appl.logger.setLevel(logger.level) + return appl.logger + + +def setup_logging(appl: Flask, loggable_modules: tuple[str, ...] = tuple()) -> None: + """ + Setup the loggers according to the WSGI server used to run the application. + """ + # https://datatracker.ietf.org/doc/html/draft-coar-cgi-v11-03#section-4.1.17 + # https://wsgi.readthedocs.io/en/latest/proposals-2.0.html#making-some-keys-required + # https://peps.python.org/pep-3333/#id4 + software, *_version_and_comments = os.environ.get( + "SERVER_SOFTWARE", "").split('/') + logger = gunicorn_loggers(appl) if bool(software) else dev_loggers(appl) + for _logger in ( + item for item in logger.manager.loggerDict.values() + if isinstance(item, logging.Logger)): + _logger.addFilter(lambda record: record.name in loggable_modules) + + +def create_app(config: Optional[dict] = None) -> Flask: """Create and return a new flask application.""" app = Flask(__name__) # ====== Setup configuration ====== app.config.from_object(settings) # Default settings - # Override defaults with startup settings - app.config.update(config or {}) # Override app settings with site-local settings if "GN_AUTH_CONF" in os.environ: app.config.from_envvar("GN_AUTH_CONF") override_settings_with_envvars(app) + # Override defaults with startup settings + app.config.update(config or {}) load_secrets_conf(app) # ====== END: Setup configuration ====== - setup_logging(app) + setup_logging(app, tuple(app.config.get("LOGGABLE_MODULES", []))) check_mandatory_settings(app) setup_oauth2_server(app) |
