Created
November 20, 2024 19:43
-
-
Save dmarticus/f686268ec3826bc6f8427f7fabcdb2b9 to your computer and use it in GitHub Desktop.
Script that uses the PostHog Python SDK to call feature flags
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import json | |
| import backoff | |
| import logging | |
| from posthog import Posthog | |
| # SingletonMeta implementation | |
| class SingletonMeta(type): | |
| _instances = {} | |
| def __call__(cls, *args, **kwargs): | |
| if cls not in cls._instances: | |
| cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs) | |
| return cls._instances[cls] | |
| # Set up logging | |
| logger = logging.getLogger(__name__) | |
| logging.basicConfig(level=logging.INFO) | |
| class PosthogClient(metaclass=SingletonMeta): | |
| _posthog: Posthog | |
| def __init__(self): | |
| api_key = os.environ.get("POSTHOG_API_KEY", "") | |
| host = os.environ.get("POSTHOG_HOST", "https://us.posthog.com") | |
| if not api_key or not host: | |
| raise ValueError("Posthog API key or host not found") | |
| self._posthog = Posthog(api_key, host, debug=True) | |
| @backoff.on_exception(backoff.expo, Exception, max_time=7, raise_on_giveup=True) | |
| def get_feature_flag(self, feature_flag_key, distinct_id): | |
| example_variant = self._posthog.get_feature_flag(key=feature_flag_key, distinct_id=distinct_id) | |
| logger.info(f"Feature flag value: {example_variant}") | |
| return example_variant | |
| @backoff.on_exception(backoff.expo, Exception, max_tries=2, raise_on_giveup=True) | |
| def get_feature_flag_payload( | |
| self, feature_flag_key, distinct_id, payload_key=None | |
| ): | |
| payload = self._posthog.get_feature_flag_payload( | |
| key=feature_flag_key, distinct_id=distinct_id | |
| ) | |
| logger.info(f"Feature flag payload: {payload}") | |
| if payload: | |
| if not payload_key: | |
| return payload | |
| try: | |
| payload = json.loads(payload) | |
| return payload.get(payload_key) | |
| except json.JSONDecodeError: | |
| logger.error( | |
| "Failed to parse feature flag payload", | |
| extra={ | |
| "feature flag": feature_flag_key, | |
| "user id": distinct_id, | |
| "payload": payload, | |
| "payload key": payload_key, | |
| }, | |
| ) | |
| return None | |
| def main(): | |
| # Prompt for PostHog API key and host if not set in environment variables | |
| api_key = os.environ.get("POSTHOG_API_KEY") | |
| if not api_key: | |
| api_key = input("Enter your PostHog API Key: ") | |
| os.environ["POSTHOG_API_KEY"] = api_key | |
| host = os.environ.get("POSTHOG_HOST") | |
| if not host: | |
| host = input("Enter your PostHog Host (e.g., https://app.posthog.com): ") | |
| os.environ["POSTHOG_HOST"] = host | |
| # Create an instance of PosthogClient | |
| client = PosthogClient() | |
| # Prompt for feature flag key and user ID | |
| feature_flag_key = input("Enter feature flag key: ") | |
| distinct_id = input("Enter user ID: ") | |
| # Get feature flag value | |
| try: | |
| flag_value = client.get_feature_flag(feature_flag_key, distinct_id) | |
| print(f"Feature flag '{feature_flag_key}' value for user '{distinct_id}': {flag_value}") | |
| except Exception as e: | |
| print(f"Error getting feature flag: {e}") | |
| # Get feature flag payload | |
| try: | |
| payload = client.get_feature_flag_payload(feature_flag_key, distinct_id) | |
| print(f"Feature flag payload for '{feature_flag_key}' and user '{distinct_id}': {payload}") | |
| except Exception as e: | |
| print(f"Error getting feature flag payload: {e}") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment