File: __init__.py

package info (click to toggle)
python-django-waffle 4.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 684 kB
  • sloc: python: 3,266; makefile: 139; sh: 39; javascript: 34
file content (70 lines) | stat: -rwxr-xr-x 2,214 bytes parent folder | download
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
from __future__ import annotations

from typing import TYPE_CHECKING

from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest

from waffle.utils import get_setting
from django.apps import apps as django_apps

if TYPE_CHECKING:
    from waffle.models import AbstractBaseFlag, AbstractBaseSample, AbstractBaseSwitch

__version__ = '4.2.0'


def flag_is_active(request: HttpRequest, flag_name: str, read_only: bool = False) -> bool | None:
    flag = get_waffle_flag_model().get(flag_name)
    return flag.is_active(request, read_only=read_only)


def switch_is_active(switch_name: str) -> bool:
    switch = get_waffle_switch_model().get(switch_name)
    return switch.is_active()


def sample_is_active(sample_name: str) -> bool:
    sample = get_waffle_sample_model().get(sample_name)
    return sample.is_active()


def get_waffle_flag_model() -> type[AbstractBaseFlag]:
    return get_waffle_model('FLAG_MODEL')


def get_waffle_switch_model() -> type[AbstractBaseSwitch]:
    return get_waffle_model('SWITCH_MODEL')


def get_waffle_sample_model() -> type[AbstractBaseSample]:
    return get_waffle_model('SAMPLE_MODEL')


def get_waffle_model(setting_name: str) -> (
    type[AbstractBaseFlag | AbstractBaseSwitch | AbstractBaseSample]
):
    """
    Returns the waffle Flag model that is active in this project.
    """
    default_model = {
        'FLAG_MODEL': 'waffle.Flag',
        'SWITCH_MODEL': 'waffle.Switch',
        'SAMPLE_MODEL': 'waffle.Sample',
    }

    # Add backwards compatibility by not requiring adding of model setting
    # for everyone who upgrades.  At some point it would be helpful to
    # require this to be defined explicitly, but no for now, to remove
    # pain from upgrading.
    default = default_model[setting_name]
    flag_model_name = get_setting(setting_name, default)

    try:
        return django_apps.get_model(flag_model_name)
    except ValueError:
        raise ImproperlyConfigured(f"WAFFLE_{setting_name} must be of the form 'app_label.model_name'")
    except LookupError:
        raise ImproperlyConfigured(
            f"WAFFLE_{setting_name} refers to model '{flag_model_name}' that has not been installed"
        )