~homeworkprod/byceps

ref: bcef32cd2dc329bcf81057794883008f5c040ac8 byceps/byceps/services/global_setting/service.py -rw-r--r-- 2.0 KiB
bcef32cd — Jochen Kupperschmidt Work around Jinja 3.0.0 bug with `for` inside of `set` block 8 months 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
"""
byceps.services.global_setting.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from __future__ import annotations
from typing import Optional

from ...database import db, upsert

from .dbmodels import Setting as DbSetting
from .transfer.models import GlobalSetting


def create_setting(name: str, value: str) -> GlobalSetting:
    """Create a global setting."""
    setting = DbSetting(name, value)

    db.session.add(setting)
    db.session.commit()

    return _db_entity_to_global_setting(setting)


def create_or_update_setting(name: str, value: str) -> GlobalSetting:
    """Create or update a global setting, depending on whether it
    already exists or not.
    """
    table = DbSetting.__table__
    identifier = {'name': name }
    replacement = {'value': value}

    upsert(table, identifier, replacement)

    return find_setting(name)


def remove_setting(name: str) -> None:
    """Remove the global setting with that name.

    Do nothing if no global setting with that name exists.
    """
    db.session.query(DbSetting) \
        .filter_by(name=name) \
        .delete()
    db.session.commit()


def find_setting(name: str) -> Optional[GlobalSetting]:
    """Return the global setting with that name, or `None` if not found."""
    setting = DbSetting.query.get(name)

    if setting is None:
        return None

    return _db_entity_to_global_setting(setting)


def find_setting_value(name: str) -> Optional[str]:
    """Return the value of the global setting with that name, or `None`
    if not found.
    """
    setting = find_setting(name)

    if setting is None:
        return None

    return setting.value


def get_settings() -> set[GlobalSetting]:
    """Return all global settings."""
    settings = DbSetting.query.all()

    return {_db_entity_to_global_setting(setting) for setting in settings}


def _db_entity_to_global_setting(setting: DbSetting) -> GlobalSetting:
    return GlobalSetting(
        setting.name,
        setting.value,
    )