Skip to content

Latest commit

 

History

History
278 lines (196 loc) · 9.1 KB

README.md

File metadata and controls

278 lines (196 loc) · 9.1 KB

Reflag Python SDK

Typed, server-side Boolean and JSON feature flags.

Installation

Install from PyPI:

pip install reflag

Support

  • Python 3.11+, including tested Python 3.14.
  • Works with synchronous and async applications, including FastAPI.

Getting started

Set your server-side secret key:

export REFLAG_SECRET_KEY="your-server-secret-key"

Create one client per application worker and reuse it across requests. Initialize it at startup and close it at shutdown. The with block below represents that application lifetime, not a single request.

For each request, call client.bind(...) with that request's user and company. Binding is cheap and reuses the shared client.

from reflag import Client

with Client() as client:
    flags = client.bind(
        {
            "user": {"id": "user-123", "email": "ada@example.com"},
            "company": {
                "id": "company-123",
                "name": "Acme",
                "attributes": {"plan": "enterprise"},
            },
        }
    )

    # Boolean flag, with False as the fallback.
    enabled = flags.get_flag("my-flag")

    # JSON flag, with an object as the fallback.
    settings = flags.get_flag("settings", default={"theme": "light"})

Targeting rules match on id, name, email and any attributes. Attributes are flattened, so attributes={"plan": "enterprise"} is matched as the company's plan.

Defaults and types

get_flag() returns your default (or False if you don't pass one) when:

  • the flag doesn't exist, for example because of a typo in the key;
  • the flag's value has a different JSON type from the default (a warning is logged);
  • flag definitions haven't loaded.

The default also sets the return type for type checkers: a bool default returns bool, a dict default returns dict[str, JSONValue], and str, number and list defaults work the same way.

Startup and status

Initialization waits for the first flag definitions to load. Subsequent flag reads are local and in-memory.

If Reflag can't be reached at startup, the client doesn't raise. Instead, client.status is "degraded" and flag reads return their defaults, or "fallback" if a fallback provider supplied saved definitions. Check client.status in a health check if you need to know whether definitions are loaded.

Async applications

Use AsyncClient with async with in your application's lifespan. Flag reads remain synchronous: call flags.get_flag(...) without await. See the FastAPI example for a complete web application.

Forking servers and workers

A client can only be used in the process that created it; using it after a fork raises RuntimeError. This affects gunicorn (especially with --preload), uWSGI, Celery's prefork pool and multiprocessing.

Create the client inside each worker after it forks, for example in gunicorn's post_fork hook or Celery's worker_process_init signal, and close it when the worker exits. ASGI lifespans, as in the FastAPI example, already run once per worker.

Telemetry

Context and flag-check telemetry is enabled by default. To disable it for a bound context, use client.bind(context, telemetry=False).

Keep your secret key on the server, never in browser code.

High performance flag targeting

The client downloads flag definitions when it initializes. get_flag() and get_flags() then evaluate flags locally against the bound context, so flag reads make no network requests and are fast even for hot code paths.

The client keeps definitions up to date in the background. Telemetry is batched and deduplicated in the background too. Closing the client sends pending events; call flush() to send them sooner.

Fallback providers

A fallback provider saves the latest flag definitions to durable storage, so a new process can still start if Reflag is unreachable during startup.

Reflag remains the source of truth. The client always fetches live definitions first and saves a snapshot through the provider after each update. It loads the saved snapshot only if that first fetch fails, and client.status is then "fallback" until live definitions load. Without a provider, a running client still keeps its last definitions in memory.

Static fallbacks can contain Boolean or JSON values:

from reflag import Client, StaticFallback

with Client(
    fallback_provider=StaticFallback(
        {"new-dashboard": False, "dashboard-settings": {"theme": "light"}}
    ),
) as client:
    settings = client.get_flag("dashboard-settings", default={})

File fallback:

from reflag import Client, FileFallback

with Client(fallback_provider=FileFallback("/var/lib/my-app/reflag")) as client:
    enabled = client.get_flag("new-dashboard")

To store snapshots elsewhere, such as Redis or S3, implement load and save. Use namespace as the storage key, and store the snapshot unchanged. AsyncClient also accepts providers with async methods.

import json
from collections.abc import Mapping

from redis import Redis


class RedisFallback:
    def __init__(self, redis: Redis) -> None:
        self._redis = redis

    def load(self, namespace: str) -> Mapping[str, object] | None:
        value = self._redis.get(f"reflag:flags-fallback:{namespace}")
        return None if value is None else json.loads(value)

    def save(self, namespace: str, snapshot: Mapping[str, object]) -> None:
        self._redis.set(f"reflag:flags-fallback:{namespace}", json.dumps(snapshot))

Testing

In offline mode the client needs no secret key, makes no network requests and sends no telemetry. Flags return their defaults unless you override them. Set REFLAG_OFFLINE=true so that application code calling Client() works unchanged, or pass offline=True.

from reflag import Client

with Client(
    offline=True,
    flag_overrides={"new-dashboard": True, "dashboard-settings": {"theme": "dark"}},
) as client:
    flags = client.bind({"company": {"id": "company-123"}})
    assert flags.get_flag("new-dashboard") is True

    # Replace the base overrides.
    client.set_flag_overrides({"new-dashboard": False})
    assert flags.get_flag("new-dashboard") is False

    # Layer scoped overrides on top; they're removed when the block exits.
    with client.override_flags(
        lambda context: {"new-dashboard": context["company"]["id"] == "company-123"}
    ):
        assert flags.get_flag("new-dashboard") is True

    client.clear_flag_overrides()
    assert flags.get_flag("new-dashboard") is False

Overrides map flag keys to JSON values. They can also be a function that receives the evaluation context and returns that map. Scoped overrides from override_flags() take precedence over base overrides and apply only in the current thread or async task.

Overrides apply after evaluation, so overriding a flag doesn't change the results of other flags that depend on it. They also work in online mode, for example during local development.

Bootstrapping browser clients

To render a page with flags already evaluated, get bootstrap state on the server and pass the whole object to the Reflag Browser SDK's bootstrappedState option. This requires Browser SDK v2 or a framework SDK built on it.

import json

from reflag import Client

with Client() as client:
    flags = client.bind({"user": {"id": "user-123"}, "company": {"id": "company-123"}})
    bootstrap = flags.get_flags_for_bootstrap()
    bootstrap_json = json.dumps(bootstrap)  # Embed this in the page.

Bootstrap state includes only flags that aren't marked secret in Reflag, plus the full context you bound, so every user, company and other attribute in it is visible to the browser. Bootstrap with a context that contains only what the client may see. Getting bootstrap state doesn't record flag checks.

FastAPI

Install the SDK and web server, then set your server-side secret key:

pip install reflag fastapi uvicorn
export REFLAG_SECRET_KEY="your-server-secret-key"

Create app.py:

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request

from reflag import AsyncClient


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    # One shared client per worker, initialized at startup and closed at shutdown.
    async with AsyncClient() as client:
        app.state.reflag = client
        yield


app = FastAPI(lifespan=lifespan)


@app.get("/companies/{company_id}/dashboard")
async def dashboard(company_id: str, request: Request) -> dict[str, object]:
    client: AsyncClient = request.app.state.reflag  # app.state is untyped.
    flags = client.bind({"company": {"id": company_id}})

    # Boolean flag; defaults to False.
    enabled = flags.get_flag("new-dashboard")

    # JSON flag with an object fallback.
    settings = flags.get_flag("dashboard-settings", default={"theme": "light"})

    return {
        "dashboard": "new" if enabled else "classic",
        "settings": settings,
    }

The shared client keeps flag definitions up to date. Flag reads are local and synchronous, so get_flag() does not need await.