Python SDK

Python server-side SDK with Django, FastAPI, and Flask integrations

Python SDK

The entrolytics-python-client package provides server-side analytics tracking for Python applications with first-class support for Django, FastAPI, and Flask.

Installation

pip install entrolytics

Quick Start

Install the Package

pip install entrolytics-python-client

Create a Client

from entrolytics_python_client import Entrolytics

client = Entrolytics(api_key="ent_xxx")

Track Events

# Track custom event
client.track(
    website_id="your-website-id",
    event="purchase",
    data={
        "revenue": 99.99,
        "currency": "USD",
        "product": "pro-plan"
    }
)

# Track page view
client.page_view(
    website_id="your-website-id",
    url="/pricing",
    referrer="https://google.com"
)

# Identify user
client.identify(
    website_id="your-website-id",
    user_id="user_456",
    traits={
        "email": "user@example.com",
        "plan": "pro"
    }
)

Async Support

Use AsyncEntrolytics for async/await applications:

from entrolytics import AsyncEntrolytics

async def track_purchase():
    async with AsyncEntrolytics(api_key="ent_xxx") as client:
        await client.track(
            website_id="abc123",
            event="purchase",
            data={"revenue": 99.99, "currency": "USD"}
        )

# Or without context manager
client = AsyncEntrolytics(api_key="ent_xxx")
await client.track(website_id="abc123", event="signup")
await client.close()

Framework Integrations

Django Setup

Configure Settings

Add to your settings.py:

settings.py
INSTALLED_APPS = [
    # ... your apps
]

MIDDLEWARE = [
    'entrolytics.django.EntrolyticsMiddleware',  # Add for auto page tracking
    # ... other middleware
]

ENTROLYTICS = {
    'WEBSITE_ID': 'your-website-id',
    'API_KEY': 'ent_xxx',
    'TRACK_ADMIN': False,  # Skip admin pages
    'EXCLUDED_PATHS': ['/health', '/api/internal/'],
}

Track Events in Views

views.py
from entrolytics.django import track, identify
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

def purchase_view(request):
    # Process purchase...

    # Track event
    track('purchase', {
        'revenue': 99.99,
        'currency': 'USD',
        'product_id': request.POST.get('product_id')
    }, request=request)

    return JsonResponse({'status': 'success'})

@login_required
def profile_view(request):
    # Identify user
    identify(str(request.user.pk), {
        'email': request.user.email,
        'username': request.user.username,
        'plan': request.user.profile.subscription_plan
    })

    return render(request, 'profile.html')

Class-Based Views

from django.views import View
from entrolytics.django import track

class PurchaseView(View):
    def _post(self, request):
        # Process purchase...

        track('purchase', {
            'amount': amount,
            'currency': 'USD'
        }, request=request)

        return JsonResponse({'success': True})

API Reference

Entrolytics Client

class Entrolytics:
    def __init__(
        self,
        api_key: str,
        host: str = "https://entrolytics.dev",
        timeout: float = 10.0
    )

Methods

track(website_id, event, data=None, **kwargs)

Track a custom event.

ParameterTypeRequiredDescription
website_idstrYesWebsite ID
eventstrYesEvent name
datadictNoEvent data
urlstrNoPage URL
referrerstrNoReferrer URL
user_idstrNoUser ID
session_idstrNoSession ID
user_agentstrNoUser agent
ip_addressstrNoClient IP

page_view(website_id, url, **kwargs)

Track a page view.

ParameterTypeRequiredDescription
website_idstrYesWebsite ID
urlstrYesPage URL
referrerstrNoReferrer URL
titlestrNoPage title
user_idstrNoUser ID

identify(website_id, user_id, traits=None)

Identify a user.

ParameterTypeRequiredDescription
website_idstrYesWebsite ID
user_idstrYesUser ID
traitsdictNoUser traits

Phase 2: Web Vitals

track_vital(website_id, metric, value, rating, **kwargs)

Track Core Web Vitals metrics.

ParameterTypeRequiredDescription
website_idstrYesWebsite ID
metricVitalMetricYesVital type (LCP, INP, CLS, TTFB, FCP)
valuefloatYesMetric value
ratingVitalRatingYesRating (good, needs-improvement, poor)
deltafloatNoDifference from previous
idstrNoUnique identifier
navigation_typeNavigationTypeNoNavigation type
attributiondictNoDebug attribution
urlstrNoPage URL
pathstrNoURL path
session_idstrNoSession ID
from entrolytics import Entrolytics

client = Entrolytics(api_key="ent_xxx")

client.track_vital(
    website_id="abc123",
    metric="LCP",
    value=2500.0,
    rating="good",
    url="https://example.com/page",
    path="/page"
)

Phase 2: Form Analytics

track_form_event(website_id, event_type, form_id, url_path, **kwargs)

Track form interaction events.

ParameterTypeRequiredDescription
website_idstrYesWebsite ID
event_typeFormEventTypeYesEvent type (start, field_focus, field_blur, submit, abandon, validation_error)
form_idstrYesForm identifier
url_pathstrYesPage path
form_namestrNoHuman-readable form name
field_namestrNoField name
field_typestrNoInput type
field_indexintNoField position
time_on_fieldintNoms spent on field
time_since_startintNoms since form start
error_messagestrNoValidation error
successboolNoSubmission success
session_idstrNoSession ID
client.track_form_event(
    website_id="abc123",
    event_type="submit",
    form_id="contact-form",
    url_path="/contact",
    form_name="Contact Form",
    success=True,
    time_since_start=45000
)

Phase 2: Deployment Tracking

set_deployment(website_id, deploy_id, **kwargs)

Register deployment context.

ParameterTypeRequiredDescription
website_idstrYesWebsite ID
deploy_idstrYesDeployment ID
git_shastrNoGit commit SHA
git_branchstrNoGit branch
deploy_urlstrNoDeployment URL
sourceDeploymentSourceNoPlatform (vercel, netlify, etc.)
client.set_deployment(
    website_id="abc123",
    deploy_id="deploy_456",
    git_sha="abc1234567890",
    git_branch="main",
    source="vercel"
)

Advanced Usage

Type Hints

Full type hint support:

from typing import Dict, Optional
from entrolytics import Entrolytics

client: Entrolytics = Entrolytics(api_key="ent_xxx")

event_data: Dict[str, any] = {
    "revenue": 99.99,
    "currency": "USD"
}

client.track(
    website_id="abc123",
    event="purchase",
    data=event_data,
    user_id="user_123"
)

# Type hints for traits
traits: Dict[str, str] = {
    "email": "user@example.com",
    "plan": "pro"
}

client.identify(
    website_id="abc123",
    user_id="user_123",
    traits=traits
)

Requirements

  • Python >= 3.9
  • httpx >= 0.25.0

Optional Dependencies

  • Django >= 4.0 (for Django integration)
  • FastAPI >= 0.100.0, Starlette >= 0.27.0 (for FastAPI integration)
  • Flask >= 2.0 (for Flask integration)

Features

  • ✅ Synchronous and async support (Entrolytics and AsyncEntrolytics)
  • ✅ Django middleware and helpers
  • ✅ FastAPI middleware and dependency injection
  • ✅ Flask extension
  • ✅ Type hints with mypy support
  • ✅ Comprehensive error handling
  • ✅ Request context extraction
  • ✅ Phase 2: Web Vitals tracking
  • ✅ Phase 2: Form Analytics
  • ✅ Phase 2: Deployment tracking
  • ✅ Custom HTTP client support
  • ✅ Self-hosted instance support

Support