forked from cfpb/django-flags
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecorators.py
46 lines (34 loc) · 1.48 KB
/
decorators.py
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
import inspect
import warnings
from django.http import Http404
from django.utils.functional import wraps
from flags.state import flag_state
def flag_check(flag_name, state, fallback=None, **fc_kwargs):
"""Check that a given flag has the given state.
If the state does not match, perform the fallback."""
def decorator(func):
# At decoration-time, ensure that the fallback for the decorated
# function has the same argspec
if fallback is not None:
func_argspec = inspect.getfullargspec(func)
fallback_argspec = inspect.getfullargspec(fallback)
if func_argspec.args != fallback_argspec.args:
warnings.warn(
"Feature flag check fallback for "
+ func.__name__
+ " takes different arguments.",
RuntimeWarning,
stacklevel=2,
)
def inner(request, *args, **kwargs):
enabled = flag_state(flag_name, request=request, **fc_kwargs)
if (state and enabled) or (not state and not enabled):
return func(request, *args, **kwargs)
elif fallback is not None:
return fallback(request, *args, **kwargs)
else:
raise Http404
return wraps(func)(inner)
return decorator
def flag_required(flag_name, fallback_view=None, pass_if_set=True):
return flag_check(flag_name, pass_if_set, fallback=fallback_view)