0
# Mixpanel
1
2
The official Mixpanel library for Python provides comprehensive server-side integration with Mixpanel analytics services. It enables tracking events, managing user profiles, and handling group analytics through a simple and intuitive API, with support for both synchronous and buffered data transmission modes.
3
4
## Package Information
5
6
- **Package Name**: mixpanel
7
- **Language**: Python
8
- **Installation**: `pip install mixpanel`
9
10
## Core Imports
11
12
```python
13
from mixpanel import Mixpanel
14
```
15
16
Complete import with all classes and utilities:
17
18
```python
19
from mixpanel import (
20
Mixpanel, Consumer, BufferedConsumer, MixpanelException,
21
DatetimeSerializer, json_dumps, __version__
22
)
23
```
24
25
For custom consumer configurations:
26
27
```python
28
from mixpanel import Mixpanel, Consumer, BufferedConsumer
29
```
30
31
For error handling:
32
33
```python
34
from mixpanel import Mixpanel, MixpanelException
35
```
36
37
## Basic Usage
38
39
```python
40
from mixpanel import Mixpanel
41
42
# Initialize with your project token
43
mp = Mixpanel("YOUR_PROJECT_TOKEN")
44
45
# Track an event
46
mp.track("user_123", "button_clicked", {
47
"button_name": "signup",
48
"page": "homepage"
49
})
50
51
# Set user profile properties
52
mp.people_set("user_123", {
53
"$first_name": "John",
54
"$last_name": "Doe",
55
"$email": "john@example.com",
56
"plan": "premium"
57
})
58
59
# Track revenue
60
mp.people_track_charge("user_123", 29.99, {
61
"item": "premium_plan",
62
"currency": "USD"
63
})
64
```
65
66
## Architecture
67
68
The Mixpanel library follows a consumer-based architecture that separates data collection from data transmission:
69
70
- **Mixpanel**: Primary class for tracking events and user profiles, delegates sending to consumers
71
- **Consumer**: Sends HTTP requests directly to Mixpanel, one per call (default behavior)
72
- **BufferedConsumer**: Maintains buffers and sends messages in batches for improved performance
73
- **MixpanelException**: Handles communication errors and API failures
74
75
This design enables flexible data transmission patterns while maintaining a simple API for common use cases.
76
77
## Capabilities
78
79
### Event Tracking
80
81
Track user events with properties and metadata, including support for historical data import for events older than 5 days.
82
83
```python { .api }
84
def track(distinct_id: str, event_name: str, properties: dict = None, meta: dict = None): ...
85
def import_data(api_key: str, distinct_id: str, event_name: str, timestamp: int, properties: dict = None, meta: dict = None, api_secret: str = None): ...
86
```
87
88
[Event Tracking](./event-tracking.md)
89
90
### People Analytics
91
92
Manage user profiles with comprehensive property operations including setting, incrementing, appending to lists, and revenue tracking.
93
94
```python { .api }
95
def people_set(distinct_id: str, properties: dict, meta: dict = None): ...
96
def people_increment(distinct_id: str, properties: dict, meta: dict = None): ...
97
def people_track_charge(distinct_id: str, amount: float, properties: dict = None, meta: dict = None): ...
98
```
99
100
[People Analytics](./people-analytics.md)
101
102
### Identity Management
103
104
Create aliases and merge user identities to handle user identification across different stages of the user lifecycle.
105
106
```python { .api }
107
def alias(alias_id: str, original: str, meta: dict = None): ...
108
def merge(api_key: str, distinct_id1: str, distinct_id2: str, meta: dict = None, api_secret: str = None): ...
109
```
110
111
[Identity Management](./identity-management.md)
112
113
### Group Analytics
114
115
Manage group profiles for organization-level analytics, supporting company profiles, team properties, and group-based segmentation.
116
117
```python { .api }
118
def group_set(group_key: str, group_id: str, properties: dict, meta: dict = None): ...
119
def group_union(group_key: str, group_id: str, properties: dict, meta: dict = None): ...
120
```
121
122
[Group Analytics](./group-analytics.md)
123
124
### Consumer Configuration
125
126
Configure data transmission behavior with direct HTTP consumers or buffered consumers for batch processing.
127
128
```python { .api }
129
class Consumer:
130
def __init__(self, events_url: str = None, people_url: str = None, import_url: str = None, request_timeout: int = None, groups_url: str = None, api_host: str = "api.mixpanel.com", retry_limit: int = 4, retry_backoff_factor: float = 0.25, verify_cert: bool = True): ...
131
132
class BufferedConsumer:
133
def __init__(self, max_size: int = 50, events_url: str = None, people_url: str = None, import_url: str = None, request_timeout: int = None, groups_url: str = None, api_host: str = "api.mixpanel.com", retry_limit: int = 4, retry_backoff_factor: float = 0.25, verify_cert: bool = True): ...
134
```
135
136
[Consumer Configuration](./consumer-configuration.md)
137
138
## Types
139
140
```python { .api }
141
class Mixpanel:
142
def __init__(self, token: str, consumer: Consumer = None, serializer: json.JSONEncoder = DatetimeSerializer):
143
"""
144
Create a Mixpanel tracking instance.
145
146
Parameters:
147
- token (str): Your project's Mixpanel token
148
- consumer (Consumer, optional): Custom consumer for data transmission (default: Consumer())
149
- serializer (json.JSONEncoder, optional): JSON encoder subclass for serialization (default: DatetimeSerializer)
150
"""
151
152
class MixpanelException(Exception):
153
"""Raised by consumers when unable to send messages.
154
155
This could be caused by a network outage or interruption, or by an invalid
156
endpoint passed to Consumer.send().
157
"""
158
pass
159
160
class DatetimeSerializer(json.JSONEncoder):
161
"""JSON encoder that handles datetime objects by converting them to ISO format strings."""
162
def default(self, obj):
163
"""
164
Convert datetime objects to string format '%Y-%m-%dT%H:%M:%S'.
165
166
Parameters:
167
- obj: Object to serialize
168
169
Returns:
170
str: Formatted datetime string or default JSON encoding
171
"""
172
173
def json_dumps(data, cls: json.JSONEncoder = None) -> str:
174
"""JSON serialization utility function with compact formatting.
175
176
Parameters:
177
- data: Data to serialize
178
- cls (json.JSONEncoder, optional): Custom encoder class
179
180
Returns:
181
str: JSON string with separators=(',', ':') for compact output
182
"""
183
184
# Version constants
185
__version__: str = "4.11.1"
186
VERSION: str = "4.11.1" # Deprecated, use __version__ instead
187
188
# Module logger
189
logger: logging.Logger # Package logger instance for debugging and monitoring
190
```