Python SDK
DebugBundle Python SDK for Django, Flask, FastAPI, and stdlib.
The Python SDK is live on PyPI as debugbundle-python and follows the same universal capture, redaction, probe, and 5xx request-failure rules as the other shipped DebugBundle SDKs.
Installation
pip install debugbundle-pythonInitialize
import os
import debugbundle
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])Configuration
| Option | Type | Default | Description |
|---|---|---|---|
project_token | str | — | Required. Project token for ingestion auth (dbundle_proj_...). |
environment | str | auto-detect | production, staging, development, etc. |
service | str | auto-detect | Service name for multi-service projects. |
enabled | bool | True | Kill switch — set to False to disable all capture. |
redact_fields | list[str] | Default set | Additional field names to redact before transmission. |
sample_rate | float | 1.0 | Event sampling rate (0.0–1.0). |
batch_size | int | 50 | Max events per batch. |
flush_interval | int | 2000 | Max milliseconds before batch send. |
endpoint | str | https://api.debugbundle.com/v1/events | Ingestion endpoint URL. |
transport | str | http | http or file (local-only mode). |
local_events_dir | str | .debugbundle/local/events | Directory for file transport output. |
Vanilla Hooks
The Python SDK provides opt-in hooks for automatic capture:
import debugbundle
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])
# Capture unhandled exceptions via sys.excepthook
debugbundle.capture_exceptions()
# Capture Python logging → DebugBundle events
debugbundle.capture_logging()
# Capture asyncio loop exception handler
debugbundle.capture_async()Each hook is independently enabled. All three can run together.
Framework Integrations
Django
# settings.py
MIDDLEWARE = [
"debugbundle.integrations.django.DebugBundleMiddleware",
# ... other middleware
]
DEBUGBUNDLE = {
"project_token": os.environ["DEBUGBUNDLE_TOKEN"],
"service": "django-api",
}The middleware captures unhandled exceptions and attaches request context (method, path, status code, headers) automatically.
Flask
from flask import Flask
import debugbundle
from debugbundle.integrations.flask import init_flask
app = Flask(__name__)
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])
init_flask(app)init_flask registers an errorhandler(Exception) and a before_request hook for request context capture.
FastAPI
from fastapi import FastAPI
import debugbundle
from debugbundle.integrations.fastapi import DebugBundleMiddleware
app = FastAPI()
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])
app.add_middleware(DebugBundleMiddleware)The ASGI middleware captures exceptions and request/response data. Works with Starlette-based frameworks.
Browser Relay
The Python SDK includes a full browser relay handler for Django, Flask, and FastAPI applications that also load @debugbundle/sdk-browser.
debugbundle.BrowserRelayHandlerexposes the framework-agnostic core handler.debugbundle.create_django_relay_view(...)returns a Django view forPOST /debugbundle/browser.debugbundle.create_flask_relay_handler(...)registers the relay route on a Flask app.debugbundle.create_fastapi_relay_handler(...)registers the relay route on a FastAPI app.
import os
from debugbundle.integrations import create_flask_relay_handler
register_relay = create_flask_relay_handler(
allowed_origins=["https://app.example.com"],
project_mode="connected",
project_token=os.environ["DEBUGBUNDLE_TOKEN"],
endpoint="https://api.debugbundle.com/v1/events",
)
register_relay(app)The relay handler validates same-origin or configured allowed origins, requires Content-Type: application/json, accepts the canonical batch request shape, rejects bodies larger than 256 KB, applies per-IP rate limiting, strips trust-sensitive headers and fields, forces sdk_name to @debugbundle/sdk-browser, and preserves browser correlation fields (request_id, trace_id, session_id, and user_id_hash) when they are strings or null.
Delivery modes match the other shipped server SDKs:
project_mode="local-only"writes accepted browser events to.debugbundle/local/events/.project_mode="connected"with the defaultdurable_write=Truewrites a durable relay spool record and then forwards with the server-side project token.project_mode="connected"withdurable_write=Falseuses the lower-latency forward-only path.
Logger Integrations
stdlib logging
import logging
import debugbundle
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])
handler = debugbundle.LoggingHandler(level=logging.ERROR)
logging.getLogger().addHandler(handler)structlog
import structlog
import debugbundle
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])
structlog.configure(
processors=[
# ... other processors
debugbundle.integrations.structlog.debugbundle_processor,
structlog.dev.ConsoleRenderer(),
]
)loguru
from loguru import logger
import debugbundle
debugbundle.init(project_token=os.environ["DEBUGBUNDLE_TOKEN"])
logger.add(debugbundle.integrations.loguru.debugbundle_sink, level="ERROR")Capture Methods
import debugbundle
# Capture an exception with optional context
try:
riskyOperation()
except Exception as e:
debugbundle.capture_exception(e, {"user_id": "usr_123"})
# Capture a structured log event
debugbundle.capture_log("Payment processing failed", "error", {
"order_id": "ord_456",
"amount": 99.99,
})
# Capture HTTP request/response pair
debugbundle.capture_request(request, response, {"route": "/api/orders"})
# Capture a diagnostic message
debugbundle.capture_message("Deployment started", "info")
# Set persistent context for all future events
debugbundle.set_context("deployment", {"version": "1.4.2"})
# Probe — diagnostic ring buffer
debugbundle.probe("db_pool", lambda: {"active": pool.active, "idle": pool.idle})
# Flush all buffered events
await debugbundle.flush()Transport
| Mode | When Used | Description |
|---|---|---|
http | Default | Sends events to the ingestion API via HTTPS. |
file | Local-only | Writes events to .debugbundle/local/events/ for CLI processing. |
The transport is selected automatically based on your connection.json mode, or can be overridden with the transport config option.
Volume Control
The Python SDK implements the same volume controls as all DebugBundle SDKs:
- Duplicate suppression — First 3 identical events in a 30-second window sent normally; subsequent duplicates aggregated into a single
error_suppressedevent. - Loop protection — More than 10 identical errors in 2 seconds forces suppression. Checkpoint every 30 seconds. Resets after 60 seconds of silence.
- Buffer retention — Events are never dropped on transport failure. Respects
Retry-Afterheaders from the ingestion API.
Next Steps
- Universal SDK Interface — Full interface contract across all SDKs
- Browser Relay Setup — Shared browser relay contract and deployment guidance
- CLI Local Workflow — Process captured events locally
- API Ingestion — Direct event ingestion API