Passed
Push — main ( ec08a4...d10783 )
by Jochen
02:20
created

byceps.config.integration.AppMode.is_metrics()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
"""
2
byceps.config.integration
3
~~~~~~~~~~~~~~~~~~~~~~~~~
4
5
:Copyright: 2014-2024 Jochen Kupperschmidt
6
:License: Revised BSD (see `LICENSE` file for details)
7
"""
8
9
from enum import Enum
10
import json
11
import os
12
13
from flask import Flask
14
15
from .errors import ConfigurationError
16
17
18
class AppMode(Enum):
19
    admin = object()
20
    api = object()
21
    base = object()
22
    cli = object()
23
    metrics = object()
24
    site = object()
25
    worker = object()
26
27
    def is_admin(self) -> bool:
28
        return self == AppMode.admin
29
30
    def is_api(self) -> bool:
31
        return self == AppMode.api
32
33
    def is_base(self) -> bool:
34
        return self == AppMode.base
35
36
    def is_cli(self) -> bool:
37
        return self == AppMode.cli
38
39
    def is_metrics(self) -> bool:
40
        return self == AppMode.metrics
41
42
    def is_site(self) -> bool:
43
        return self == AppMode.site
44
45
    def is_worker(self) -> bool:
46
        return self == AppMode.worker
47
48
    def __repr__(self) -> str:
49
        return f'{self.__class__.__name__}[{self.name}]'
50
51
52
def init_app(app: Flask) -> None:
53
    app.byceps_app_mode = _determine_app_mode(app)
54
55
    if app.byceps_app_mode.is_site():
56
        if not app.config.get('SITE_ID'):
57
            raise ConfigurationError('No site ID configured.')
58
59
60
def _determine_app_mode(app: Flask) -> AppMode:
61
    value = app.config.get('APP_MODE', 'base')
62
63
    try:
64
        return AppMode[value]
65
    except KeyError as exc:
66
        raise ConfigurationError(
67
            f'Invalid app mode "{value}" configured.'
68
        ) from exc
69
70
71
def parse_value_from_environment(
72
    key: str,
73
) -> bool | dict | float | int | list | str | None:
74
    value = os.environ.get(key)
75
    if value is None:
76
        return None
77
78
    try:
79
        # Detect booleans, numbers, collections, `null`/`None`.
80
        return json.loads(value)
81
    except Exception:
82
        # Leave it as a string.
83
        return value
84