|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import json |
| 4 | +import sys |
| 5 | +from urllib.error import HTTPError, URLError |
| 6 | +from urllib.request import Request, urlopen |
| 7 | + |
| 8 | +from featurevisor import create_instance |
| 9 | + |
| 10 | +DATAFILE_URL = "https://featurevisor-example-cloudflare.pages.dev/production/featurevisor-tag-all.json" |
| 11 | +FEATURE_KEY = "my_feature" |
| 12 | +CONTEXT = { |
| 13 | + "userId": "123", |
| 14 | + "deviceId": "device-23456", |
| 15 | + "country": "nl", |
| 16 | +} |
| 17 | + |
| 18 | + |
| 19 | +def fetch_datafile(url: str) -> dict: |
| 20 | + try: |
| 21 | + request = Request( |
| 22 | + url, |
| 23 | + headers={ |
| 24 | + "User-Agent": "featurevisor-example-python/1.0", |
| 25 | + "Accept": "application/json", |
| 26 | + }, |
| 27 | + ) |
| 28 | + with urlopen(request) as response: |
| 29 | + return json.load(response) |
| 30 | + except HTTPError as exc: |
| 31 | + raise RuntimeError(f"failed to fetch datafile: HTTP {exc.code}") from exc |
| 32 | + except URLError as exc: |
| 33 | + raise RuntimeError(f"failed to fetch datafile: {exc.reason}") from exc |
| 34 | + |
| 35 | + |
| 36 | +def main() -> int: |
| 37 | + try: |
| 38 | + datafile = fetch_datafile(DATAFILE_URL) |
| 39 | + f = create_instance({"datafile": datafile, "logLevel": "error"}) |
| 40 | + f.set_context(CONTEXT) |
| 41 | + enabled = f.is_enabled(FEATURE_KEY) |
| 42 | + except Exception as exc: |
| 43 | + print(f"Error: {exc}", file=sys.stderr) |
| 44 | + return 1 |
| 45 | + |
| 46 | + print(f"Datafile revision: {f.get_revision()}") |
| 47 | + print(f"Context: {json.dumps(CONTEXT)}") |
| 48 | + print(f"Feature '{FEATURE_KEY}' enabled: {enabled}") |
| 49 | + print(f"All evaluations: {json.dumps(f.get_all_evaluations(), sort_keys=True)}") |
| 50 | + return 0 |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + raise SystemExit(main()) |
0 commit comments