Skip to content

Python SDK

Last updated View as MarkdownAgent setup

The Python SDK provides an OpenFeature-compatible FlagshipServerProvider for server-side Python applications. It evaluates flags over HTTP or locally from downloaded flag definitions. It does not support the Cloudflare Workers binding.

Installation

Install with uv or pip:

uv add cloudflare-flagship
pip install cloudflare-flagship

Setup

Configure the provider with your Flagship app ID, Cloudflare account ID, and an API token with Flagship Evaluate or Flagship App Evaluate permission.

from openfeature import api
from openfeature.evaluation_context import EvaluationContext
from flagship import FlagshipServerProvider

api.set_provider(
    FlagshipServerProvider(
        app_id="<APP_ID>",
        account_id="<ACCOUNT_ID>",
        auth_token="<API_TOKEN>",
    )
)

client = api.get_client()
enabled = client.get_boolean_value(
    "new-checkout",
    False,
    EvaluationContext(targeting_key="user-42", attributes={"plan": "enterprise"}),
)

Flag types

The Python SDK supports all OpenFeature flag types. Python's OpenFeature SDK separates numeric values into integer and float methods.

enabled = client.get_boolean_value("new-checkout", False, context)
variant = client.get_string_value("homepage-hero", "control", context)
limit = client.get_integer_value("upload-limit", 10, context)
rate = client.get_float_value("sample-rate", 0.1, context)
config = client.get_object_value("ui-config", {"theme": "light"}, context)

Use the *_details methods when you need the resolved value, reason, variant, or error code.

Configuration options

Option Type Default Description
app_id str None Flagship app ID.
account_id str None Required with app_id, and always required for local evaluation.
auth_token str None Bearer token added to every request.
headers_factory Callable[[], dict[str, str]] None Dynamic per-request headers.
timeout float 5.0 Request timeout in seconds.
retries int 1 Retry attempts on transient errors, capped at 10.
retry_delay float 1.0 Delay between retries in seconds, capped at 30.0.
local_evaluation bool False Download flag definitions and evaluate flags in-process.
refresh_interval float 30.0 Seconds between background definition refreshes.
logging bool False Enable SDK-level debug output through the SDK logger.
cache_ttl float None Cache TTL in seconds. Enables caching when set.
cache_max_size int 1000 Maximum cached entries before least-recently-used eviction.

Local evaluation

With local evaluation, the provider downloads the app's flag definitions and evaluates flags in-process. No network request is made per evaluation. The provider refreshes the definitions on a background daemon thread.

Local evaluation requires an API token with Flagship Read or Flagship App Read permission. Local evaluations do not appear in Flagship analytics.

api.set_provider_and_wait(
    FlagshipServerProvider(
        app_id="<APP_ID>",
        account_id="<ACCOUNT_ID>",
        auth_token="<READ_API_TOKEN>",
        local_evaluation=True,
        refresh_interval=30.0,
    )
)

Use set_provider_and_wait so the first definitions download completes before you evaluate flags. If the first download fails, initialization raises an error and the provider reports the ERROR status. If a background refresh fails, the provider keeps serving the last downloaded definitions.

Local evaluation cannot be combined with cache_ttl. account_id is always required. If you set endpoint instead of app_id, the URL path must end in /evaluate so the provider can derive the definitions URL.

Local evaluation does not enforce the Flagship request size limits on evaluation context. The Flagship API rejects very large contexts, but local evaluation evaluates them.

Response caching

Server-side response caching is off by default. Enable it with cache_ttl when you want repeated evaluations for the same flag, type, and evaluation context to reuse a recent result.

FlagshipServerProvider(
    app_id="<APP_ID>",
    account_id="<ACCOUNT_ID>",
    auth_token="<API_TOKEN>",
    cache_ttl=30.0,
    cache_max_size=1000,
)

Cached values may be stale until the TTL expires. Keep the TTL short for flags that you expect to change during active rollouts. The provider does not cache disabled flags or errors.

Evaluation context

From version 0.6.0, context attributes can contain strings, integers, finite floats, booleans, None, dictionaries with string keys, lists, and tuples. The provider recursively normalizes datetime values to ISO 8601 strings.

The provider sends structured context using POST with a JSON body. Context containing only strings, numbers, booleans, or datetimes uses GET query parameters. Unsupported values, non-finite numbers, and cycles raise InvalidContextError.

Async evaluation

The async API mirrors the sync API:

enabled = await client.get_boolean_value_async("new-checkout", False, context)
details = await client.get_boolean_details_async("new-checkout", False, context)

When shutting down in an async context, use shutdown_async():

await api.shutdown_async()

Was this helpful?