Completed
Push — master ( 0943a5...c65a32 )
by Jochen
04:29
created

byceps.config._determine_site_id()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
"""
2
byceps.config
3
~~~~~~~~~~~~~
4
5
:Copyright: 2006-2019 Jochen Kupperschmidt
6
:License: Modified BSD, see LICENSE for details.
7
"""
8
9
from enum import Enum
10
11
from flask import current_app
12
13
14
EXTENSION_KEY = 'byceps_config'
15
KEY_SITE_MODE = 'site_mode'
16
KEY_SITE_ID = 'site_id'
17
18
19
SiteMode = Enum('SiteMode', ['public', 'admin'])
20
SiteMode.is_admin = lambda self: self == SiteMode.admin
21
SiteMode.is_public = lambda self: self == SiteMode.public
22
23
24
class ConfigurationError(Exception):
25
    pass
26
27
28
def init_app(app):
29
    app.extensions[EXTENSION_KEY] = {}
30
31
    site_mode = _determine_site_mode(app)
32
    update_extension_value(app, KEY_SITE_MODE, site_mode)
33
34
    if site_mode.is_public():
35
        site_id = _determine_site_id(app)
36
        update_extension_value(app, KEY_SITE_ID, site_id)
37
38
39
def update_extension_value(app, key, value):
40
    """Set/replace the value value for the key in this application's
41
    own extension namespace.
42
    """
43
    app.extensions[EXTENSION_KEY][key] = value
44
45
46
# -------------------------------------------------------------------- #
47
# site mode
48
49
50
def _determine_site_mode(app):
51
    value = app.config.get('SITE_MODE')
52
    if value is None:
53
        raise ConfigurationError('No site mode configured.')
54
55
    try:
56
        return SiteMode[value]
57
    except KeyError:
58
        raise ConfigurationError(f'Invalid site mode "{value}" configured.')
59
60
61
def get_site_mode(app=None):
62
    """Return the mode the site should run in."""
63
    return _get_config_dict(app)[KEY_SITE_MODE]
64
65
66
# -------------------------------------------------------------------- #
67
# site ID
68
69
70
def _determine_site_id(app):
71
    site_id = app.config.get('SITE_ID')
72
    if site_id is None:
73
        raise ConfigurationError('No site ID configured.')
74
75
    return site_id
76
77
78
def get_current_site_id(app=None):
79
    """Return the id of the current site."""
80
    return _get_config_dict(app)[KEY_SITE_ID]
81
82
83
# -------------------------------------------------------------------- #
84
85
86
def _get_config_dict(app=None):
87
    if app is None:
88
        app = current_app
89
90
    return app.extensions[EXTENSION_KEY]
91