A while ago I posted on how to add feature flags to a nodeJS application using only a flat file + OpenFeature.
Here's how to do the same thing for Python!
Install Packages
pip install openfeature-provider-flagd
Create flags.json
Define the feature flag (in this case a single flag called background-colour
and save as flags.json
:
{ "$schema": "https://flagd.dev/schema/v0/flags.json", "flags": { "background-colour": { "state": "ENABLED", "variants": { "white": "#D6D4D2", "green": "#73A53E", "orange": "#FF7C00", "lime": "#D3D309", "blue": "#4AB9D9" }, "defaultVariant": "green" } } }
The Code
Save this as app.py
:
from openfeature import api from openfeature.contrib.provider.flagd import FlagdProvider from openfeature.contrib.provider.flagd.config import ResolverType import time api.set_provider(FlagdProvider( resolver_type=ResolverType.IN_PROCESS, offline_flag_source_path="flags.json", )) client = api.get_client("my-app") while True: try: colour = client.get_string_value(flag_key="background-colour", default_value="NA") print(f"The current colour is: {colour}") finally: time.sleep(1)
Run Program
Go ahead and start the program: python app.py
This should print the Hex colour value once per second:
The current colour is: #73A53E The current colour is: #73A53E The current colour is: #73A53E
Leave the program running and change the defaultVariant
in flags.json
from "green"
to "lime"
(remember to save the changes) and the program should automatically refresh:
The current colour is: #73A53E The current colour is: #73A53E The current colour is: #D3D309 The current colour is: #D3D309 The current colour is: #D3D309
Summary
This method uses the in process evaluation of the open source feature flag system flagd + OpenFeature to build a feature flagging ability in Python.
Find out more about the in process evaluation engine for flagd and OpenFeature here.
Top comments (0)