aboutsummaryrefslogtreecommitdiff
path: root/scripts/qcapp_wsgi.py
blob: fe77031a5d84a438baee69813bc4dc2a54560769 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""Run the application"""
import os
import sys
from logging import getLogger, StreamHandler

from flask import Flask

from uploader import create_app
from uploader.check_connections import check_db, check_redis

def setup_logging(appl: Flask) -> Flask:
    """Setup appropriate logging paradigm depending on environment."""
    # 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('/')
    if bool(software):
        gunicorn_logger = getLogger("gunicorn.error")
        appl.logger.handlers = gunicorn_logger.handlers
        appl.logger.setLevel(gunicorn_logger.level)#pylint: disable=[no-member]
    else:
        loglevel = appl.config["LOG_LEVEL"].upper()
        # Maybe call `logging.dictConfig(…)` here instead of all this stuff below
        handler_stderr = StreamHandler(stream=sys.stderr)
        appl.logger.addHandler(handler_stderr)
        rootlogger = getLogger()
        rootlogger.addHandler(handler_stderr)
        rootlogger.setLevel(loglevel)
        appl.logger.setLevel(loglevel)

    return appl


def check_and_build_app() -> Flask:
    """Setup the application for running."""
    # Setup the app
    appl = create_app()

    # Check connections
    check_db(appl.config["SQL_URI"])
    check_redis(appl.config["REDIS_URL"])
    return setup_logging(appl)


app = check_and_build_app()

if __name__ == "__main__":
    # Run the app
    app.run()