Python
Send events from Python backends and read your stats, sync or async.
The stancelens package uses only the standard library (urllib); the async client uses httpx when it's installed. Python 3.9+, fully typed.
Not on PyPI yet. Install it from the Stancelens repository: pip install ./packages/python (add [httpx] for the async transport).
You need an API key from an owner or admin of the site. Keep it on the server: it can write events and erase users.
Track events
from stancelens import Stancelens
client = Stancelens(api_key="el_live_...", site_id="SITE_ID")
client.track("signup", uid="user_42", props={"plan": "pro"})
client.identify("user_42", {"company": "Acme"}, vid=anon_id_from_browser) # vid optional
client.revenue("purchase", 49.0, "USD", uid="user_42")
client.pageview("https://example.com/pricing", ip=request_ip, ua=user_agent)These calls only add the event to an in-memory queue. A daemon thread sends the queue as a batch when flush_at events are waiting or every flush_interval seconds, at most 100 events per request. On normal interpreter exit the client flushes itself (atexit). That hook doesn't run when the process is killed by a signal, so call client.shutdown() from your own SIGTERM handler, and client.flush() at the end of short-lived jobs such as serverless handlers.
Identity
Every event needs at least one of uid, vid or ip; with none, the call raises ValueError.
vid, an anonymous visitor ID you manage, is used as given.- Without
vidbut withip(and ideallyua), the server derives the same daily-rotating anonymous ID the browser script uses. IP addresses aren't stored. - With only
uid, the uid is also used as the visitor ID, so one user's events stay together.
Event fields
track(name, *, uid, vid, props, revenue, url, path, referrer, title, ts, ip, ua,
language, timezone, duration, app_version)props: flat dict of strings, numbers, booleans orNone(up to 50 keys).revenue: a number, or{"amount": 9.99, "currency": "EUR"}.ts:datetime(naive means UTC) or epoch milliseconds. Defaults to the time of the call; the server accepts up to 30 days in the past.ua: with a user agent the server fills in browser, OS and device, and drops known bots.- Country isn't looked up from
ip. Passtimezone(an IANA name like"Europe/Berlin") for the server's time-zone-based country estimate.
Every event is sent with platform: "server" and sdk: "stancelens-python/<version>". A page view that carries a browser's user agent is recorded as web, so server-side page views count with browser traffic; everything else is server.
Options
Stancelens(
api_key, site_id,
host="https://stancelens.com",
flush_at=20, # send when this many events are queued
flush_interval=5.0, # seconds
max_queue_size=10_000, # further events are dropped (and counted) while full
max_retries=3, # network errors, 408, 429 and 5xx (honours Retry-After)
timeout=10.0, # per request, seconds
on_error=None, # callable(exception, events) for batches that weren't delivered
disabled=False, # True: accept calls, send nothing (tests, local dev)
register_atexit=True,
)client.droppedcounts events that weren't stored: queue full, rejected after retries, or refused by the server (a bot user agent, an excluded path).client.flush(timeout)blocks until the queue is sent and returnsFalseif the timeout passed first.client.shutdown()(aliasclose(), also used bywith Stancelens(...) as client:) flushes and stops the thread; later calls are dropped.- Send errors are never raised into your code. Without
on_errorthey're logged on thestancelenslogger.
Async
from stancelens import AsyncStancelens
async with AsyncStancelens(api_key="el_live_...", site_id="SITE_ID") as client:
client.track("export_finished", uid="user_42") # not awaited: it only queues
await client.flush()
stats = await client.stats.aggregate(period="7d")Same track, pageview, identify and revenue methods, called inside a running event loop (the first call starts a background flush task; calling outside a loop raises RuntimeError). await client.flush() sends now, await client.aclose() flushes and closes. It uses httpx.AsyncClient when httpx is installed and otherwise runs urllib in a worker thread; force one with use_httpx=True or False, and check client.transport.
Read stats
client.stats.aggregate(period="30d", metrics=["visitors", "pageviews", "revenue"], compare="previous")
client.stats.timeseries(period="7d", interval="day")
client.stats.breakdown("path", limit=10, page=1, filters={"country": ["US", "DE"]})
client.stats.breakdown("props.plan", date_from="2026-01-01", date_to="2026-01-31")
client.stats.realtime()
client.stats.export(period="today", filters={"user_id": "user_42"}) # raw events, JSON
client.stats.delete_user("user_42") # GDPR erasure- Methods return plain dicts shaped like the REST API responses (
TypedDicts instancelens.responses) and raisestancelens.APIError(with.statusand.body) for non-2xx answers. period:today,yesterday,24h,7d,30d(server default),mtd,lastmonth,90d,6mo,12mo,ytd,all, in the site timezone (details).date_from/date_to(dateor"YYYY-MM-DD", inclusive) switch to a custom range.filters:{dimension: value}. A list means any of; prefix!to exclude and~for contains, e.g.{"path": "~/blog", "browser": "!Safari"}. Dimensions are the API filter dimensions.- Reads work with a key of any member who can view the site; sending events and
delete_userneed an owner or admin key.
Server-side page views
The framework integrations record a pageview for each successful (2xx) GET that returns text/html and isn't a browser prefetch, with the visitor's IP, user agent, referrer and language. They never raise into your request. Use them instead of the browser script for those pages, not together with it, or page views are counted twice.
The IP is the socket peer address by default. Behind a reverse proxy that sets X-Forwarded-For, pass trust_proxy=True (Django: "trust_proxy": True).
from stancelens.integrations.flask import init_app
init_app(app, client, get_uid=lambda: str(current_user.id) if current_user.is_authenticated else None)- ASGI:
get_uid(scope)andshould_track(scope)are optional callables. - Django: signed-in users are sent as
uid(request.user.pk). OtherSTANCELENSkeys are passed toStancelens(...), andstancelens.integrations.django.get_client()returns the same client for your owntrackcalls.