惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
IT之家
IT之家
F
Fortinet All Blogs
腾讯CDC
酷 壳 – CoolShell
酷 壳 – CoolShell
月光博客
月光博客
GbyAI
GbyAI
Recent Announcements
Recent Announcements
博客园 - 叶小钗
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 司徒正美
Y
Y Combinator Blog
人人都是产品经理
人人都是产品经理
N
Netflix TechBlog - Medium
博客园_首页
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
爱范儿
爱范儿
F
Full Disclosure
博客园 - 【当耐特】
V
V2EX
M
MIT News - Artificial intelligence
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
Google Developers Blog
Stack Overflow Blog
Stack Overflow Blog
D
DataBreaches.Net
Martin Fowler
Martin Fowler
Cisco Talos Blog
Cisco Talos Blog
大猫的无限游戏
大猫的无限游戏
T
The Blog of Author Tim Ferriss
S
Schneier on Security
Latest news
Latest news
S
Secure Thoughts
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
Apple Machine Learning Research
Apple Machine Learning Research
T
Tenable Blog
Blog — PlanetScale
Blog — PlanetScale
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cyberwarzone
Cyberwarzone
Spread Privacy
Spread Privacy
K
Kaspersky official blog
L
Lohrmann on Cybersecurity
宝玉的分享
宝玉的分享
A
About on SuperTechFans
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
P
Palo Alto Networks Blog
Microsoft Azure Blog
Microsoft Azure Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Feature Flags in Python: Django, FastAPI & Flask Guide
Domenico Gio · 2026-04-24 · via DEV Community

This was originally published on rollgate.io/blog/feature-flags-python.

Why Feature Flags in Python?

Python powers everything from web applications and REST APIs to data pipelines and machine learning systems. Across all of these, you face the same challenge: how do you ship new features safely without risky deployments?

Feature flags solve this by decoupling deployment from release. You deploy code with the feature wrapped in a conditional, then control who sees it — without touching your codebase.

Here is where feature flags shine in Python projects:

  • Web applications — Roll out new UI components or API endpoints to a subset of users in Django, FastAPI, or Flask.
  • REST APIs — Version API behavior dynamically without maintaining separate endpoints.
  • Data pipelines — Toggle new ETL logic or processing steps without redeploying Airflow DAGs.
  • ML model rollouts — A/B test model versions in production, compare accuracy, and roll back instantly if metrics degrade.

If you have ever been burned by a production deploy that broke something for all users at once, feature flags are the safety net you need.

Quick Start: Feature Flags with the Rollgate Python SDK

The fastest way to add feature flags to any Python application is with the Rollgate Python SDK. Install it with pip:

pip install rollgate-python

Enter fullscreen mode Exit fullscreen mode

Initialize the client and start evaluating flags:

from rollgate import RollgateClient

# Initialize once at application startup
client = RollgateClient(
    sdk_key="your-sdk-key",
    options={
        "poll_interval": 30,  # refresh flags every 30 seconds
    }
)

# Evaluate a boolean flag
if client.is_enabled("new-dashboard", default=False):
    show_new_dashboard()
else:
    show_legacy_dashboard()

# Evaluate with user context for targeting
user_context = {
    "key": "user-123",
    "email": "alice@example.com",
    "plan": "pro",
    "country": "IT",
}

if client.is_enabled("beta-feature", context=user_context):
    enable_beta(user_context["key"])

Enter fullscreen mode Exit fullscreen mode

The client fetches flag configurations from Rollgate and caches them locally. Evaluations happen in-memory with no network calls, so they add virtually zero latency to your application.

You can get your SDK key by creating a free Rollgate account.

The Simple Approach: Environment Variables

Before reaching for a feature flag service, many teams start with environment variables:

import os

NEW_CHECKOUT = os.getenv("FF_NEW_CHECKOUT", "false").lower() == "true"

def process_order(order):
    if NEW_CHECKOUT:
        return new_checkout_flow(order)
    return legacy_checkout_flow(order)

Enter fullscreen mode Exit fullscreen mode

This works for simple on/off switches, but it hits limitations fast:

  • Requires a redeploy to change a flag value.
  • No gradual rollouts — it is all-or-nothing for every user.
  • No user targeting — you cannot enable a feature for specific users or segments.
  • No audit trail — who changed what and when?
  • No instant rollback — reverting means changing the env var and redeploying.

Environment variables are fine for infrastructure configuration (DATABASE_URL, LOG_LEVEL). For feature releases, you need something more flexible.

Feature Flags in Django

Django applications benefit from feature flags at multiple layers: middleware, views, templates, and Django REST Framework serializers.

Middleware

Apply feature flags globally across all requests:

# myapp/middleware.py
from rollgate import RollgateClient

client = RollgateClient(sdk_key="your-sdk-key")

class FeatureFlagMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        context = {}
        if request.user.is_authenticated:
            context = {
                "key": str(request.user.id),
                "email": request.user.email,
                "plan": getattr(request.user, "plan", "free"),
            }

        request.feature_flags = {
            "new_nav": client.is_enabled("new-nav", context=context),
            "dark_mode": client.is_enabled("dark-mode", context=context),
        }

        return self.get_response(request)

Enter fullscreen mode Exit fullscreen mode

View Decorator

Create a reusable decorator for protecting views behind flags:

# myapp/decorators.py
from functools import wraps
from django.http import Http404

def feature_required(flag_name: str):
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            context = {"key": str(request.user.id)} if request.user.is_authenticated else {}
            if not client.is_enabled(flag_name, context=context):
                raise Http404
            return view_func(request, *args, **kwargs)
        return wrapper
    return decorator

# Usage
@feature_required("new-analytics")
def analytics_view(request):
    return render(request, "analytics/new.html")

Enter fullscreen mode Exit fullscreen mode

Template Tags

Expose flags directly in Django templates:

# myapp/templatetags/feature_flags.py
from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def feature_enabled(context, flag_name: str) -> bool:
    request = context.get("request")
    if request and hasattr(request, "feature_flags"):
        return request.feature_flags.get(flag_name, False)
    return False

Enter fullscreen mode Exit fullscreen mode

{% load feature_flags %}

{% feature_enabled "new-nav" as show_new_nav %}
{% if show_new_nav %}
    {% include "nav/new_nav.html" %}
{% else %}
    {% include "nav/legacy_nav.html" %}
{% endif %}

Enter fullscreen mode Exit fullscreen mode

Django REST Framework

Use flags in DRF views and serializers to control API behavior:

# myapp/views.py
from rest_framework.views import APIView
from rest_framework.response import Response

class ProductListView(APIView):
    def get(self, request):
        context = {"key": str(request.user.id), "plan": request.user.plan}

        if client.is_enabled("v2-product-response", context=context):
            serializer = ProductV2Serializer(products, many=True)
        else:
            serializer = ProductV1Serializer(products, many=True)

        return Response(serializer.data)

Enter fullscreen mode Exit fullscreen mode

Feature Flags in FastAPI

FastAPI's dependency injection system makes feature flags clean and testable.

Dependency Injection Pattern

# app/dependencies.py
from fastapi import Depends, HTTPException, Request
from rollgate import RollgateClient

client = RollgateClient(sdk_key="your-sdk-key")

def get_flag_context(request: Request) -> dict:
    user = request.state.user if hasattr(request.state, "user") else None
    if user:
        return {"key": user.id, "email": user.email, "plan": user.plan}
    return {}

def require_feature(flag_name: str):
    def dependency(context: dict = Depends(get_flag_context)):
        if not client.is_enabled(flag_name, context=context):
            raise HTTPException(status_code=404, detail="Not found")
        return True
    return dependency

Enter fullscreen mode Exit fullscreen mode

# app/routes/search.py
from fastapi import APIRouter, Depends
from app.dependencies import require_feature, get_flag_context, client

router = APIRouter()

@router.get("/search")
async def search(
    query: str,
    context: dict = Depends(get_flag_context),
):
    if client.is_enabled("ai-search", context=context):
        results = await ai_powered_search(query)
    else:
        results = await keyword_search(query)

    return {"results": results}

@router.get(
    "/search/semantic",
    dependencies=[Depends(require_feature("semantic-search"))],
)
async def semantic_search(query: str):
    """This entire endpoint is gated behind a feature flag."""
    return {"results": await run_semantic_search(query)}

Enter fullscreen mode Exit fullscreen mode

Middleware

# app/middleware.py
from starlette.middleware.base import BaseHTTPMiddleware

class FeatureFlagMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        context = {}
        if hasattr(request.state, "user"):
            context = {"key": request.state.user.id}

        request.state.flags = {
            "maintenance_mode": client.is_enabled("maintenance-mode", context=context),
        }

        if request.state.flags.get("maintenance_mode"):
            return JSONResponse(
                status_code=503,
                content={"message": "We are performing scheduled maintenance."},
            )

        return await call_next(request)

Enter fullscreen mode Exit fullscreen mode

Feature Flags in Flask

Flask's simplicity pairs well with decorator-based feature flags.

Decorator Pattern

# app/flags.py
from functools import wraps
from flask import abort, g
from rollgate import RollgateClient

client = RollgateClient(sdk_key="your-sdk-key")

def feature_required(flag_name: str):
    def decorator(f):
        @wraps(f)
        def wrapped(*args, **kwargs):
            context = {"key": str(g.user.id)} if hasattr(g, "user") else {}
            if not client.is_enabled(flag_name, context=context):
                abort(404)
            return f(*args, **kwargs)
        return wrapped
    return decorator

# Usage
@app.route("/experiments")
@feature_required("experiments-page")
def experiments():
    return render_template("experiments.html")

Enter fullscreen mode Exit fullscreen mode

before_request Hook

Evaluate flags once per request and make them available globally:

# app/__init__.py
from flask import Flask, g

app = Flask(__name__)

@app.before_request
def load_feature_flags():
    context = {}
    if hasattr(g, "user") and g.user:
        context = {
            "key": str(g.user.id),
            "email": g.user.email,
        }

    g.flags = {
        "new_pricing": client.is_enabled("new-pricing", context=context),
        "export_csv": client.is_enabled("export-csv", context=context),
    }

Enter fullscreen mode Exit fullscreen mode

<!-- templates/pricing.html -->
{% if g.flags.new_pricing %}
    {% include "pricing/new.html" %}
{% else %}
    {% include "pricing/legacy.html" %}
{% endif %}

Enter fullscreen mode Exit fullscreen mode

Gradual Rollouts

Instead of flipping a feature on for everyone, gradual rollouts let you increase exposure incrementally.

Percentage-Based Rollouts

Configure a rollout percentage in the Rollgate dashboard (for example, 10%), and the SDK handles consistent user assignment:

# The SDK uses consistent hashing on the user key.
# The same user always gets the same result for a given percentage.

context = {"key": f"user-{user_id}"}

if client.is_enabled("new-checkout", context=context):
    # This user is in the rollout group
    return new_checkout(cart)
else:
    return legacy_checkout(cart)

Enter fullscreen mode Exit fullscreen mode

A typical rollout schedule:

Day 1:   5%  → internal team + early adopters
Day 3:  25%  → monitor error rates and latency
Day 5:  50%  → check support tickets
Day 7: 100%  → full release

Enter fullscreen mode Exit fullscreen mode

If error rates spike at any stage, set the rollout back to 0% instantly from the dashboard.

User Targeting with Attributes

Target specific users or segments by passing attributes in the context:

context = {
    "key": str(user.id),
    "email": user.email,
    "plan": user.subscription.plan,       # "free", "starter", "pro"
    "country": user.profile.country,       # "US", "IT", "DE"
    "created_at": user.created_at.isoformat(),
}

# In the Rollgate dashboard, you can create rules like:
# - Enable for plan = "pro"
# - Enable for country IN ["US", "DE"]
# - Enable for 20% of free plan users

if client.is_enabled("advanced-analytics", context=context):
    return full_analytics(user)
else:
    return basic_analytics(user)

Enter fullscreen mode Exit fullscreen mode

Feature Flags for ML Model Rollouts

Machine learning models in production need careful rollout strategies. A new model might have better accuracy on your test set but degrade on edge cases in production. Feature flags let you A/B test model versions safely.

A/B Test Model Versions

from rollgate import RollgateClient

client = RollgateClient(sdk_key="your-sdk-key")

def predict(user_id: str, input_data: dict) -> dict:
    context = {"key": user_id}

    if client.is_enabled("recommendation-model-v2", context=context):
        model = load_model("recommendation_v2")
        prediction = model.predict(input_data)
        log_prediction(user_id, model="v2", prediction=prediction)
    else:
        model = load_model("recommendation_v1")
        prediction = model.predict(input_data)
        log_prediction(user_id, model="v1", prediction=prediction)

    return prediction

Enter fullscreen mode Exit fullscreen mode

Start the recommendation-model-v2 flag at 5%, monitor prediction quality metrics, and increase gradually.

Shadow Mode

Run both models simultaneously, serve the old one, and log the new one for comparison:

def predict_with_shadow(user_id: str, input_data: dict) -> dict:
    context = {"key": user_id}

    # Always run the current production model
    v1_model = load_model("recommendation_v1")
    v1_result = v1_model.predict(input_data)

    # Shadow mode: run v2 in parallel, log results, but don't serve them
    if client.is_enabled("shadow-model-v2", context=context):
        v2_model = load_model("recommendation_v2")
        v2_result = v2_model.predict(input_data)

        log_shadow_comparison(
            user_id=user_id,
            v1=v1_result,
            v2=v2_result,
            match=v1_result == v2_result,
        )

    return v1_result  # always serve v1 during shadow mode

Enter fullscreen mode Exit fullscreen mode

Once shadow mode data confirms v2 performs well, switch to the A/B test approach to serve v2 to real users.

Testing with Feature Flags

Feature flags should not make your test suite unpredictable. Use fixtures and mocks to control flag state in tests.

Pytest Fixtures

# conftest.py
import pytest
from unittest.mock import MagicMock

@pytest.fixture
def mock_rollgate():
    client = MagicMock()
    client.is_enabled.return_value = False
    return client

@pytest.fixture
def mock_rollgate_all_enabled():
    client = MagicMock()
    client.is_enabled.return_value = True
    return client

Enter fullscreen mode Exit fullscreen mode

Testing Both Code Paths

# test_checkout.py
from unittest.mock import patch

def test_legacy_checkout(mock_rollgate):
    mock_rollgate.is_enabled.return_value = False

    with patch("myapp.checkout.client", mock_rollgate):
        result = process_checkout(cart)

    assert result.flow == "legacy"

def test_new_checkout(mock_rollgate):
    mock_rollgate.is_enabled.return_value = True

    with patch("myapp.checkout.client", mock_rollgate):
        result = process_checkout(cart)

    assert result.flow == "new"

Enter fullscreen mode Exit fullscreen mode

Flag-Specific Mocking

def test_partial_flags(mock_rollgate):
    def side_effect(flag_name, **kwargs):
        enabled_flags = {"new-checkout": True, "dark-mode": False}
        return enabled_flags.get(flag_name, False)

    mock_rollgate.is_enabled.side_effect = side_effect

    with patch("myapp.views.client", mock_rollgate):
        response = app_client.get("/checkout")
        assert response.status_code == 200

Enter fullscreen mode Exit fullscreen mode

Async Support

Modern Python applications often use asyncio. The Rollgate Python SDK supports async evaluation for non-blocking flag checks:

import asyncio
from rollgate import RollgateClient

client = RollgateClient(sdk_key="your-sdk-key")

async def handle_request(user_id: str):
    context = {"key": user_id}

    # Flag evaluation is local (cached), so it's fast even in sync mode.
    # For async initialization and polling:
    if client.is_enabled("async-feature", context=context):
        result = await async_new_logic()
    else:
        result = await async_legacy_logic()

    return result

Enter fullscreen mode Exit fullscreen mode

Since flag evaluations happen against locally cached data, they are inherently fast. The async support is primarily useful for the initial flag fetch and background polling, ensuring they do not block your event loop.

# FastAPI example with async
from fastapi import FastAPI

app = FastAPI()

@app.on_event("startup")
async def startup():
    # Initialize the client at startup
    global client
    client = RollgateClient(sdk_key="your-sdk-key")

@app.get("/api/recommendations")
async def recommendations(user_id: str):
    context = {"key": user_id}

    if client.is_enabled("ml-recommendations-v2", context=context):
        return await get_ml_recommendations_v2(user_id)
    return await get_ml_recommendations_v1(user_id)

Enter fullscreen mode Exit fullscreen mode

Frequently Asked Questions

Do feature flags add latency to my Python app?

No. The Rollgate SDK fetches flag configurations on startup and polls for updates in the background. All flag evaluations happen locally in memory, adding microseconds of overhead — not milliseconds.

Can I use feature flags with Celery tasks?

Yes. Initialize the Rollgate client once in your Celery worker startup, and evaluate flags inside tasks just like you would in a view:

from celery import Celery
from rollgate import RollgateClient

app = Celery("tasks")
client = RollgateClient(sdk_key="your-sdk-key")

@app.task
def process_report(user_id: str):
    context = {"key": user_id}
    if client.is_enabled("new-report-format", context=context):
        generate_new_report(user_id)
    else:
        generate_legacy_report(user_id)

Enter fullscreen mode Exit fullscreen mode

How do I handle flags in database migrations?

Do not use feature flags in migrations. Migrations should be deterministic and repeatable. Instead, use flags in application code to control which schema or logic path is active.

What happens if the Rollgate service is unreachable?

The SDK caches the last known flag state locally. If it cannot reach Rollgate to poll for updates, it continues using cached values. You can also set default values that apply when a flag has never been fetched.

Can I use feature flags with Django's test client?

Yes. Mock the Rollgate client in your Django test setup, or use the middleware approach and override request.feature_flags directly in tests.

Start Using Feature Flags in Python

Feature flags transform how you ship Python applications. Whether you are building a Django web app, a FastAPI microservice, or a Flask API, the pattern is the same: wrap new code in a flag check, deploy safely, and control the rollout from your dashboard.

Ready to get started?

  1. Create a free Rollgate account
  2. Install the SDK: pip install rollgate-python
  3. Read the Python SDK documentation for the full API reference

No credit card required. Free tier includes 500K requests/month and unlimited flags.