Skip to main content

Python SDK

The official Python SDK for Toggly provides a comprehensive solution for feature flag management in Python applications.

Quick reference

Grab the printable Python cheat sheet (download PDF) — Django, Flask, FastAPI, async, caching.

Features​

  • Zero-dependency core - The core package has no external dependencies
  • Django integration - Middleware, template tags, decorators, and context processors
  • Flask integration - Extension, decorators, and Jinja2 template helpers
  • FastAPI integration - Middleware, dependencies, and route decorators
  • Distributed caching - Redis and Memcached support
  • Async/await support - Native async client for async frameworks
  • Type hints - Full type annotations for IDE support
  • Python 3.8+ - Core toggly supports Python 3.8 or higher
  • FastAPI package 3.9+ - toggly-fastapi requires Python 3.9+
  • Live updates - Optional WebSocket streaming via toggly[websocket]
  • Signed definitions - ES256 verification with JWKS

Installation​

pip install toggly

Quick Start​

Basic Usage​

from toggly import TogglyClient, TogglyConfig

# Configure the client
config = TogglyConfig(
app_key="your-app-key",
environment="Production",
)

client = TogglyClient(config)
client.init()

# Check if a feature is enabled
if client.is_enabled("my-feature"):
print("Feature is enabled!")
else:
print("Feature is disabled")

With User Context​

Target features to specific users or groups:

from toggly import EvaluationContext

context = EvaluationContext(
identity="user-123",
groups=["beta-testers", "premium"],
traits={
"plan": "enterprise",
"country": "US",
}
)

if client.is_enabled("premium-feature", context):
print("Premium feature enabled for this user!")

Entity context​

EvaluationContext holds user targeting and an optional, separate entity field. Map the domain object per check for Context Property filters. See Entity & page context.

Register a local mapper before creating the client. An optional EntityContextSchemaRegistration from toggly.entity_context, passed as schema=, adds a dashboard catalog schema at startup. Set register_contexts_on_startup=False to disable that upload. Browser/mobile clients never register schemas.

from dataclasses import dataclass
from toggly import EvaluationContext, TogglyEntityContext
from toggly.entity_context import register_context, map_entity

@dataclass
class Order:
id: str
vip: bool
total: float

# Register once, before creating the client.
register_context("Order", lambda order: TogglyEntityContext(
kind="Order", key=order.id,
attributes={"Vip": order.vip, "Total": order.total},
))

user_context = EvaluationContext(identity="user-123", groups=["premium"])
order = Order("order-123", True, 120.0)
order_context = user_context.with_entity(map_entity("Order", order))
if client.is_enabled("ExpressCheckout", context=order_context):
print("Express checkout is enabled for this Order")

An unregistered mapper kind returns no entity; a Context Property condition requiring that entity fails closed. Set ExpressCheckout to use kind Order and the condition Vip == true. User identity and Order identity remain separate. Framework helpers cache their first context: populate request user/entity fields before the first evaluation, and use with_entity plus a core per-call check to evaluate another Order.

Django​

# settings.py
INSTALLED_APPS = [
# ...
"toggly_django",
]

TOGGLY = {"APP_KEY": "your-app-key", "ENVIRONMENT": "Production"}

MIDDLEWARE = [
# ...
"toggly_django.middleware.TogglyMiddleware",
]
# views.py
from django.shortcuts import render
from toggly_django.decorators import feature_flag_required

@feature_flag_required("new-dashboard")
def dashboard_view(request):
return render(request, "dashboard.html")
<!-- templates/base.html; toggly-django 0.4.0+ -->
{% load toggly_tags %}

{% iffeature "new-navigation" %}
<nav>New navigation</nav>
{% endiffeature %}
{% iffeature "new-navigation" negate=True %}
<nav>Legacy navigation</nav>
{% endiffeature %}

Flask​

from flask import Flask, render_template
from toggly_flask import Toggly, feature_flag_required

app = Flask(__name__)
app.config["TOGGLY_APP_KEY"] = "your-app-key"
app.config["TOGGLY_ENVIRONMENT"] = "Production"

toggly = Toggly(app)

@app.route("/dashboard")
@feature_flag_required("new-dashboard")
def dashboard():
return render_template("dashboard.html")
{# templates/base.html #}
{% if toggly.check("new-navigation") %}
<nav>New navigation</nav>
{% else %}
<nav>Legacy navigation</nav>
{% endif %}

FastAPI​

from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends
from toggly_fastapi import configure_toggly, TogglyMiddleware, get_toggly, require_feature

@asynccontextmanager
async def lifespan(app: FastAPI):
client = configure_toggly(app_key="your-app-key", environment="Production")
try:
yield
finally:
client.close()

app = FastAPI(lifespan=lifespan)

app.add_middleware(TogglyMiddleware)

@app.get("/dashboard", dependencies=[Depends(require_feature("new-dashboard"))])
async def dashboard():
return {"message": "New dashboard!"}

@app.get("/checkout")
async def checkout(toggly = Depends(get_toggly)):
if toggly.is_enabled("new-checkout"):
return {"version": "v2"}
return {"version": "v1"}

Available Packages​

PackageDescriptionPyPI
togglyCore library with zero dependenciesPyPI
toggly-djangoDjango integrationPyPI
toggly-flaskFlask integrationPyPI
toggly-fastapiFastAPI integrationPyPI
toggly-cacheRedis/Memcached cachingPyPI

Requirements​

  • Python 3.8 or higher (core toggly)
  • Python 3.9 or higher for toggly-fastapi (requires-python = ">=3.9")
  • Django 4.2+ (for Django integration)
  • Flask 2.0+ (for Flask integration)
  • FastAPI 0.100+ (for FastAPI integration)

Learn by running and reading​

Start with a local default of False, configure that exact flag key in your application's environment, then enable it and wait for the next refresh. Follow the framework guide for executable route, template and request-context examples. The Samples catalog lists runnable projects and their setup instructions. The Python SDK source separates the core client/context modules from each framework adapter.

Next Steps​