UK-1 Datacenter
|
Back to Knowledgebase
Py
PyPI trustportidentity-beacon v1.8.0

Python & FastAPI SDK Guide

The TrustPort Beacon Python SDK (trustportidentity-beacon) provides simple performance monitoring for FastAPI, Django, and Flask applications.

1Install Package

Install via pip or poetry:

pip install trustportidentity-beacon

2FastAPI ASGI Blueprint

main.pyPython 3.10+
import os
from fastapi import FastAPI, Request
from trustportidentity_beacon import BeaconMiddleware, beacon_span

app = FastAPI(title="Sovereign AI Engine")

# Register ASGI Telemetry Middleware
app.add_middleware(
    BeaconMiddleware,
    ingest_url="https://beacon-api.trustportidentity.com",
    api_key=os.environ["BEACON_API_KEY"],  # tb_live_...
    service_name="python-ml-service",
    environment="production"
)

@app.get("/health")
async def health():
    return {"status": "healthy"}

@app.post("/api/v1/predict")
async def predict(request: Request):
    # Contextual child span for model inference
    with beacon_span("ml.inference.bert_classifier") as span:
        span.set_tag("model_version", "v2.4")
        # Perform computation...
        return {"label": "fintech_risk_low", "confidence": 0.98}

3Django & Celery Setup

Django settings.py

Add "trustportidentity_beacon.django.BeaconMiddleware" to your Django MIDDLEWARE array, then set BEACON_INGEST_URL / BEACON_API_KEY / BEACON_SERVICE_NAME in your settings.

4Control Ingest Volume with sample_rate

Every request is already batched (batch_size/flush_interval) instead of one network call per request. On top of that, pass sample_rate (0–1, default 1.0) to trace only a fraction of requests in high-traffic services β€” this is what actually keeps you inside your plan's monthly quota. Exceptions are always sent regardless of sampling. Django: set BEACON_SAMPLE_RATE in settings.py.

BeaconMiddleware(app, ..., sample_rate=0.2) # trace ~20% of requests
Questions about Gunicorn / Uvicorn worker settings?

Our engineers can help configure multi-process fork hooks.

Consult Python Architect