Python SDK
Follow these instructions to track and enrich events from a Python-based framework, such as FastAPI or Django.
Installation
To install the Sumatra Python SDK:
pip install sumatra-sdk
Sync or Async
How you send events to Sumatra from Python depends on whether you are using a synchronous and asynchronous server.
import sumatra
sumatra.api_key = "SUMATRA_API_KEY"
sumatra.api_uri = "https://api.sumatra.ai"
# track
sumatra.track("event_type", **data)
# enrich
response = sumatra.enrich("event_type", **data)
import sumatra
async with sumatra.SDKClient(api_key="SUMATRA_API_KEY", api_uri="https://api.sumatra.ai") as client:
# track
await client.track_async("event_type", **data)
# enrich
response = await client.enrich_async("event_type", **data)
The response dictionary will contain all of the features
computed by your Scowl code. See the API response docs for the full details.
Synchronous Example
Here is a realistic example of how the Python SDK may be called by a synchronous backend to decide whether or not to allow a user to sign up:
# server.py
import sumatra
sumatra.api_key = "ak_BcNtzouCjOfoxWkxw9wvYt0O"
features = sumatra.enrich("signup", {
"email": "user@example.com",
"ip": "205.12.234.7",
"name": "Darrel Smith",
"browser": {"language": "en-US"},
},
)
if features["verdict"] == "Block":
... # block signup
else:
... # allow signup
Asynchronous Example
This is an example of how to use Python to send events to Sumatra using the asynchronous API and FastAPI. Your implementation may vary.
from fastapi import Depends, FastAPI
from sumatra import SDKClient
import dotenv
import os
app = FastAPI()
async def get_client() -> SDKClient:
"""Load your api key and event url somehow, and yield a client object with that configuration"""
dotenv.load_dotenv()
api_key = os.environ["SUMATRA_API_KEY"]
event_url = os.environ["SUMATRA_API_EVENT_URL"]
async with SDKClient(event_url=event_url, api_key=api_key) as c:
yield c
@app.get("/{name}")
async def route(
name: str,
sumatra: SDKClient = Depends(get_client)
):
enriched = await sumatra.enrich_async("my_event", name=name)
return {"message": f"Hello {name}!", "extra": enriched}