Statsig Python Server SDK

0.71.6 · active · verified Thu Apr 09

The Statsig Python Server SDK enables developers to integrate feature flags, A/B tests, and dynamic configurations into their Python applications. It provides server-side evaluation of gates and experiments, ensuring consistent user experiences. The library is actively maintained with frequent minor releases, currently at version 0.71.6.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Statsig Python SDK, define a user, check a feature gate, retrieve a dynamic config, fetch an experiment, log an event, and properly shut down the SDK. Remember to replace `YOUR_SERVER_SECRET_KEY` with your actual server secret from the Statsig console, or set it via the `STATSIG_SERVER_SECRET` environment variable.

import statsig
import os
import asyncio

async def main():
    # It is crucial to use a server secret key (sk-...) for the server SDK.
    # NEVER expose client keys (pk-..., client-...) in your server-side code.
    secret_key = os.environ.get('STATSIG_SERVER_SECRET', 'YOUR_SERVER_SECRET_KEY')

    if not secret_key or secret_key == 'YOUR_SERVER_SECRET_KEY':
        print("Please set the STATSIG_SERVER_SECRET environment variable or replace 'YOUR_SERVER_SECRET_KEY' in the code.")
        return

    # Initialize the SDK. This is an asynchronous operation.
    print("Initializing Statsig SDK...")
    await statsig.initialize(secret_key)
    print("Statsig SDK initialized.")

    # Define a StatsigUser object with relevant attributes
    user = statsig.StatsigUser(
        user_id="example-user-123",
        email="user@example.com",
        country="US",
        custom={
            "plan": "premium"
        },
        private_attributes={
            "phone_number": "+15551234567"
        }
    )

    # Check a feature gate
    if statsig.check_gate(user, "my_feature_gate"):
        print("Feature 'my_feature_gate' is ON for the user.")
    else:
        print("Feature 'my_feature_gate' is OFF for the user.")

    # Get a dynamic config
    config = statsig.get_config(user, "my_dynamic_config")
    print(f"Value for 'my_dynamic_config': {config.value}")

    # Get an experiment
    experiment = statsig.get_experiment(user, "my_a_b_test")
    print(f"Value for 'my_a_b_test': {experiment.value}")

    # Log an event
    statsig.log_event(user, "product_viewed", value=10.99, metadata={"product_id": "item_xyz"})

    # Shut down the SDK. This is crucial for flushing all pending events.
    print("Shutting down Statsig SDK...")
    await statsig.shutdown()
    print("Statsig SDK shut down.")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →