CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mixpanel

Official Mixpanel library for Python providing server-side analytics tracking

Pending
Overview
Eval results
Files

event-tracking.mddocs/

Event Tracking

Event tracking functionality enables recording user actions and behaviors with comprehensive property support. Mixpanel supports both real-time event tracking and historical data import for events older than 5 days.

Capabilities

Basic Event Tracking

Track user events with properties and metadata. Events are recorded with automatic timestamp generation and unique insert IDs for deduplication.

def track(distinct_id: str, event_name: str, properties: dict = None, meta: dict = None):
    """
    Record an event.

    Parameters:
    - distinct_id (str): Identifies the user triggering the event
    - event_name (str): A name describing the event
    - properties (dict, optional): Additional data to record; keys should be strings, and values should be strings, numbers, or booleans
    - meta (dict, optional): Overrides Mixpanel special properties

    Returns:
    None
    """

Usage Example:

from mixpanel import Mixpanel

mp = Mixpanel("YOUR_PROJECT_TOKEN")

# Basic event tracking
mp.track("user_123", "page_viewed", {
    "page": "homepage",
    "referrer": "google.com",
    "device": "mobile"
})

# Event with custom properties
mp.track("user_456", "purchase", {
    "product_id": "shoe_001",
    "price": 99.99,
    "category": "footwear",
    "color": "black",
    "size": 42
})

# Event with meta overrides
mp.track("user_789", "signup", {
    "source": "facebook_ad"
}, meta={
    "time": 1609459200  # Override automatic timestamp
})

Historical Data Import

Import events that occurred more than 5 days in the past. This requires API credentials and is useful for backfilling historical data or migrating from other analytics platforms.

def import_data(api_key: str, distinct_id: str, event_name: str, timestamp: int, properties: dict = None, meta: dict = None, api_secret: str = None):
    """
    Record an event that occurred more than 5 days in the past.

    Parameters:
    - api_key (str): (DEPRECATED) Your Mixpanel project's API key
    - distinct_id (str): Identifies the user triggering the event
    - event_name (str): A name describing the event
    - timestamp (int): UTC seconds since epoch
    - properties (dict, optional): Additional data to record; keys should be strings, and values should be strings, numbers, or booleans
    - meta (dict, optional): Overrides Mixpanel special properties
    - api_secret (str, optional): Your Mixpanel project's API secret (recommended over api_key)

    Returns:
    None

    Note: The api_key parameter is deprecated. Use api_secret instead.
    """

Usage Example:

import time
from datetime import datetime, timedelta
from mixpanel import Mixpanel

mp = Mixpanel("YOUR_PROJECT_TOKEN")

# Import historical event (more than 5 days old)
historical_timestamp = int((datetime.now() - timedelta(days=30)).timestamp())

mp.import_data(
    api_key="DEPRECATED_API_KEY",  # Will be removed in future versions
    api_secret="YOUR_API_SECRET",   # Recommended approach
    distinct_id="user_123",
    event_name="historical_purchase",
    timestamp=historical_timestamp,
    properties={
        "product": "vintage_item",
        "price": 149.99,
        "imported": True
    }
)

Error Handling

Event tracking methods may raise MixpanelException when network issues occur or when the Mixpanel API returns errors.

from mixpanel import Mixpanel, MixpanelException

mp = Mixpanel("YOUR_PROJECT_TOKEN")

try:
    mp.track("user_123", "critical_event", {"value": 100})
except MixpanelException as e:
    print(f"Failed to track event: {e}")
    # Implement retry logic or fallback handling

Best Practices

Property Guidelines

  • Use consistent naming conventions for event names and properties
  • Keep property keys as strings and values as strings, numbers, or booleans
  • Avoid deeply nested objects in properties
  • Use descriptive event names that clearly indicate the user action

Performance Considerations

  • Consider using BufferedConsumer for high-volume event tracking
  • Batch related events when possible to reduce network overhead
  • Handle MixpanelException appropriately for production reliability

Data Quality

  • Ensure distinct_id values are consistent across a user's lifecycle
  • Use proper data types for properties to enable effective analysis
  • Include relevant context in event properties for better insights

Install with Tessl CLI

npx tessl i tessl/pypi-mixpanel

docs

consumer-configuration.md

event-tracking.md

group-analytics.md

identity-management.md

index.md

people-analytics.md

tile.json