|
| 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) |
0 commit comments