Passed
Push — lazy-imports ( cf51de )
by Juho
04:07
created

annif.create_app()   A

Complexity

Conditions 2

Size

Total Lines 35
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 20
nop 1
dl 0
loc 35
rs 9.4
c 0
b 0
f 0
1
#!/usr/bin/env python3
2
3
import logging
4
import os
5
import os.path
6
7
logging.basicConfig()
8
logger = logging.getLogger("annif")
9
logger.setLevel(level=logging.INFO)
10
11
import annif.backend  # noqa
12
13
14
def create_flask_app(config_name=None):
15
    """Create a Flask app to be used by the CLI."""
16
    from flask import Flask
17
18
    app = Flask(__name__)
19
    config_name = _get_config_name(config_name)
20
    logger.debug(f"creating flask app with configuration {config_name}")
21
    app.config.from_object(config_name)
22
    app.config.from_envvar("ANNIF_SETTINGS", silent=True)
23
    return app
24
25
26
def create_app(config_name=None):
27
    """ "Create a Connexion app to be used for the API."""
28
    # 'cxapp' here is the Connexion application that has a normal Flask app
29
    # as a property (cxapp.app)
30
    import connexion
31
    from flask_cors import CORS
32
33
    from annif.openapi.validation import CustomRequestBodyValidator
34
35
    specdir = os.path.join(os.path.dirname(__file__), "openapi")
36
    cxapp = connexion.App(__name__, specification_dir=specdir)
37
    config_name = _get_config_name(config_name)
38
    logger.debug(f"creating connexion app with configuration {config_name}")
39
    cxapp.app.config.from_object(config_name)
40
    cxapp.app.config.from_envvar("ANNIF_SETTINGS", silent=True)
41
42
    validator_map = {
43
        "body": CustomRequestBodyValidator,
44
    }
45
    cxapp.add_api("annif.yaml", validator_map=validator_map)
46
47
    # add CORS support
48
    CORS(cxapp.app)
49
50
    if cxapp.app.config["INITIALIZE_PROJECTS"]:
51
        annif.registry.initialize_projects(cxapp.app)
52
        logger.info("finished initializing projects")
53
54
    # register the views via blueprints
55
    from annif.views import bp
56
57
    cxapp.app.register_blueprint(bp)
58
59
    # return the Flask app
60
    return cxapp.app
61
62
63
def _get_config_name(config_name):
64
    if config_name is None:
65
        config_name = os.environ.get("ANNIF_CONFIG")
66
    if config_name is None:
67
        if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
68
            config_name = "annif.default_config.Config"
69
        else:
70
            config_name = "annif.default_config.ProductionConfig"
71
    return config_name
72