Skip to content

Commit 069f30f

Browse files
Tomas-PytelTomas-Pytel
authored andcommitted
Add feature flags
1 parent 7b35aa0 commit 069f30f

File tree

3 files changed

+88
-0
lines changed

3 files changed

+88
-0
lines changed

fastapi_featureflags/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from .main import FeatureFlags, feature_flag, feature_enabled
2+
from .router import router

fastapi_featureflags/main.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import json
2+
import requests
3+
4+
5+
class FeatureFlags(object):
6+
features = {}
7+
8+
def __init__(
9+
self,
10+
conf_from_json: str = "",
11+
conf_from_url: str = "",
12+
**kwargs,
13+
):
14+
self.handle_config(conf_from_json, conf_from_url)
15+
16+
def handle_config(self, conf_from_json, conf_from_url):
17+
if conf_from_json:
18+
with open(conf_from_json, "r") as f:
19+
params = json.loads(f.read())
20+
for k, v in params.items():
21+
self.features[k] = v
22+
elif conf_from_url:
23+
params = requests.get(conf_from_url).json()
24+
print(params)
25+
for k, v in params.items():
26+
self.features[k] = v
27+
28+
@classmethod
29+
def handle_feature(cls, feature_name):
30+
features = cls.features
31+
if features.get(feature_name, False) is False:
32+
features[feature_name] = False
33+
34+
@classmethod
35+
def is_enabled(cls, feature_name):
36+
features = cls.features
37+
return features.get(feature_name, False)
38+
39+
@classmethod
40+
def get_features(cls):
41+
return cls.features
42+
43+
@classmethod
44+
def enable_feature(cls, feature_name):
45+
cls.features[feature_name] = True
46+
return cls.features[feature_name]
47+
48+
@classmethod
49+
def disable_feature(cls, feature_name):
50+
cls.features[feature_name] = False
51+
return cls.features[feature_name]
52+
53+
54+
def feature_flag(feature_name):
55+
def decorator(function):
56+
def wrapper(*args, **kwargs):
57+
FeatureFlags.handle_feature(feature_name)
58+
if FeatureFlags.is_enabled(feature_name):
59+
# print("Feature Enabled:", feature_name)
60+
return function(*args, **kwargs)
61+
else:
62+
# print("Feature Disabled:", feature_name)
63+
return True
64+
65+
return wrapper
66+
67+
return decorator
68+
69+
70+
def feature_enabled(feature_name):
71+
FeatureFlags.handle_feature(feature_name)
72+
return FeatureFlags.is_enabled(feature_name)

fastapi_featureflags/router.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from . import FeatureFlags
2+
from fastapi import APIRouter
3+
4+
5+
router = APIRouter()
6+
7+
8+
@router.get("/all")
9+
def show_feature_flags():
10+
"""
11+
Return all feature flags
12+
:return: string
13+
"""
14+
return FeatureFlags.get_features()

0 commit comments

Comments
 (0)