~homeworkprod/byceps

ref: d29cbb41481c02bc579c88f7bf2db08baceb4300 byceps/byceps/config.py -rw-r--r-- 2.0 KiB
d29cbb41 — Jochen Kupperschmidt Inline `STATIC_URL_PREFIX_*` config values 2 years ago
                                                                                
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
byceps.config
~~~~~~~~~~~~~

:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from enum import Enum

from flask import current_app


EXTENSION_KEY = 'byceps_config'
KEY_SITE_MODE = 'site_mode'
KEY_SITE_ID = 'site_id'


SiteMode = Enum('SiteMode', ['public', 'admin'])
SiteMode.is_admin = lambda self: self == SiteMode.admin
SiteMode.is_public = lambda self: self == SiteMode.public


class ConfigurationError(Exception):
    pass


def init_app(app):
    app.extensions[EXTENSION_KEY] = {}

    site_mode = determine_site_mode(app)
    update_extension_value(app, KEY_SITE_MODE, site_mode)

    if site_mode.is_public():
        site_id = determine_site_id(app)
        update_extension_value(app, KEY_SITE_ID, site_id)


def update_extension_value(app, key, value):
    """Set/replace the value value for the key in this application's
    own extension namespace.
    """
    app.extensions[EXTENSION_KEY][key] = value


# -------------------------------------------------------------------- #
# site mode


def determine_site_mode(app):
    value = app.config.get('SITE_MODE')
    if value is None:
        raise ConfigurationError('No site mode configured.')

    try:
        return SiteMode[value]
    except KeyError:
        raise ConfigurationError(f'Invalid site mode "{value}" configured.')


def get_site_mode(app=None):
    """Return the mode the site should run in."""
    return _get_config_dict(app)[KEY_SITE_MODE]


# -------------------------------------------------------------------- #
# site ID


def determine_site_id(app):
    site_id = app.config.get('SITE_ID')
    if site_id is None:
        raise ConfigurationError('No site ID configured.')

    return site_id


def get_current_site_id(app=None):
    """Return the id of the current site."""
    return _get_config_dict(app)[KEY_SITE_ID]


# -------------------------------------------------------------------- #


def _get_config_dict(app=None):
    if app is None:
        app = current_app

    return app.extensions[EXTENSION_KEY]