Mixpanel SDKs: Python

Getting Started

The Mixpanel Python library is designed to be used for scripting, or in circumstances when a user isn’t directly interacting with your application on the web or a mobile device.

The Full API Reference, Library Source Code, and an Example Script is documented in our GitHub repo.

Installing the Library

You can get the library using pip.

# install the Mixpanel module
pip install mixpanel

Once the library is installed, import the Mixpanel object from the module, then initialize the object using your project token.

# import Mixpanel object from the module
from mixpanel import Mixpanel
 
# initialize Mixpanel
mp = Mixpanel("YOUR_PROJECT_TOKEN")

Library Configuration

The Mixpanel instance can be customized with different configurations using a custom consumer. Learn more about the consumer and the available parameters here.

Example Usage

# initialize Mixpanel
mp = mixpanel.Mixpanel(
  "YOUR_PROJECT_TOKEN",
  # use custom consumer where retry limit is set to 2
  consumer=mixpanel.Consumer(retry_limit=2),
)

Sending Events

Use track() to send an event by providing the distinct_id, event name, and any event properties. This will trigger a request to the /track API endpoint to ingest the event into your project.

The /track endpoint will only validate events with timestamps within the last 5 days of the request. Events with timestamps older than 5 days will not be ingested. See below on best practices for historical imports.

Example Usage

# import Mixpanel
from mixpanel import Mixpanel
 
# initialize Mixpanel
mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# Track 'some_event' with "plan" event prop
# With distinct_id set to '12345'
mp.track('12345', 'some_event', {
    'plan': 'premium'
})

Mixpanel determines default geolocation data ($city, $region, mp_country_code) using the IP address on the incoming request. As all server-side calls will likely originate from the same IP (that is, the IP of your server), this can have the unintended effect of setting the location of all of your users to the location of your data center. Learn more about best practices for geolocation..

Importing Historical Events

The track() function is designed for real-time tracking in a server-side environment and will trigger request to the /track API endpoint, which will validate for events with a time stamp that is within the last 5 days of the request. Events older than 5 days will not be ingested.

Use the import_data() function to import events that occured more than 5 days in the past. The import_data() function is based on the /import API endpoint.

Example Usage

# initialize Mixpanel
mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# import event that is old
mp.import_data(
	api_key='', # deprecated but required
	distinct_id='sample_distinct_id', 
	event_name='some_event',
    timestamp=1634528073,
	properties = {'some_property': 'some value'},
	api_secret = 'project_api_secret' # used to authenticate request
	)

You can also use the mp-utils python module designed for scripting.

Managing User Identity

Since the Python SDK is a server-side library, IDs are not generated by the SDK. Instead, you will need to generate and manage the distinct_id yourself and include it in your events and profile data.

Learn more about server-side identity management.

Storing User Profiles

Create user profiles by setting profile properties to describe them. Example profile properties include “name”, “email”, “company”, and any other demographic details about the user.

The Python SDK provides a few functions for setting profile properties, which will trigger requests to the /engage API endpoint.

Mixpanel determines default geolocation data ($city, $region, mp_country_code) using the IP address on the incoming request. As all server-side calls will likely originate from the same IP (that is, the IP of your server), this can have the unintended effect of setting the location of all of your users to the location of your data center. Learn more about best practices for geolocation..

Setting Profile Properties

Set profile properties on a user profile by calling the people_set() method.

If a profile property already exist, if will be overwritten with the latest value provided in the method. If a profile property does not exist, it will be added to the profile.

Example Usage

# initialize Mixpanel
mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# create a user profile with name and email props
mp.people_set('sample_distinct_id', {
    'name' : 'sam',
    '$email' : 'sam@example.com',
}, meta = {
    '$ignore_time' : True, # do not update $last_seen
    '$ip' : 0}) # do not update geolocation
 
# update name property with new value
mp.people_set('sample_distinct_id', {
    'name' : 'samantha'
}, meta = {'$ignore_time' : True,'$ip' : 0})

Other Types of Profile Updates

There are a few other methods for setting profile properties. See a complete reference of the available methods here.

A few commonly used people methods are highlighted below:

The people_set_once() method set profile properties only if they do not exist yet. If it is setting a profile property that already exists, it will be ignored.

Use this method if you want to set profile properties without the risk of overwriting existing data.

Example Usage

mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# set profile properties for user "1234"
mp.people_set('1234', {
'name':'sam'
}, meta={'$ip':0})
 
# will be ignored since "name" already exists
mp.people_set_once('1234', {
'name':'samantha'
}, meta={'$ip':0})
 
# set "location" user prop since it does not exist
mp.people_set_once('1234', {
'location':'us'
}, meta={'$ip':0})

Group Analytics

Read more about Group Analytics before proceeding. You will need to have the group key defined in your project settings first.

Mixpanel Group Analytics is a paid add-on that allows behavioral data analysis by selected groups, as opposed to individual users.

A group is identified by the group_key and group_id.

  • group_key is the event property that connects event data to a group. (e.g. company)
  • group_id is the identifier for a specific group. (e.g. mixpanel,company_a,company_b, etc.)

Sending Group Identifiers With Events

All events must have the group key as an event property in order to be attributed to a group. Without the group key, an event cannot be attributed to a group.

To send group identifiers with your events, set the group_key as an event property with the group_id as the value.

Example Usage

mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# track "some_event" with a "distinct_id"
# event is attributed to the "mixpanel" company group
mp.track('sample_distinct_id', 'some_event', {
    'Plan Type' : 'Premium', 
    'company' : 'mixpanel'})

Multiple Groups

An event can be attributed to multiple groups by passing in the group_key value as a list of multiple group_id values.

Example Usage

mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# track "some_event" with a "distinct_id"
# event is attributed to 2 comapny groups: "mp-us" and "mp-eu"
mp.track('sample_distinct_id', 'some_event', {
    'Plan Type' : 'Premium', 
    'company' : ['mp-us','mp-eu']})

Adding Group Identifiers to User Profiles

To connect group information to a user profile, include the group_key and group_id as a user profile property using the people_set() call.

Example Usage

# initialize Mixpanel
mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# set group key "company" as a user prop
# with group id "mixpanel" as value
mp.people_set('sample_distinct_id', {
    'name' : 'sam',
    'company' : 'mixpanel',
}, meta = {'$ignore_time' : True,'$ip' : 0})

Setting Group Profile Properties

Create a group profile by setting group properties, similar to a user profile. For example, you may want to describe a company group with properties such as “ARR”, “employee_count”, and “subscription”.

To set group profile properties, use the group_set() function, which will trigger a request to the /groups API endpoint.

Example Usage

mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# create group profile for the "mixpanel" company group
# set "Company Type" and "$name" group profile properties
mp.group_set('company', 'mixpanel', {
    'Company Type': 'Analytics',
     '$name': 'Mixpanel'})

Other Group Profile Methods

See all of the methods under the Group class here.

A few commonly used group methods are highlighted below:

The group_set_once() method set group profile properties only if they do not exist yet. If it is setting a profile property that already exists, it will be ignored.

Use this method if you want to set group profile properties without the risk of overwriting existing data.

Example Usage

mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# set group profile for "mixpanel" company group
mp.group_set('company','mixpanel', {
    'name': 'Mixpanel',
    'employee_count': 100
})
 
# ignored since "name" is already exists
mp.group_set_once('company','mixpanel', {
    'name': 'mp-us',
})
 
# set "location" group prop since it does not exist
mp.group_set_once('company','mixpanel', {
    'location': 'us',
})

Privacy-Friendly Tracking

You have control over the data you send to Mixpanel. The Python SDK have a few configurations to help you protect user data.

Since this is a server-side tracking library where you have control of the servers, your server is responsible for determining whether to send data about a particular user or not.

EU Data Residency

Route data to Mixpanel’s EU servers by using a custom Consumer with an api_host set to the EU domain.

Example Usage

from mixpanel import Mixpanel
 
# use custom consumer with URLs set to Mixpanel's EU domain
mp_eu = Mixpanel(
  "YOUR_PROJECT_TOKEN",
  consumer=mixpanel.Consumer(api_host="api-eu.mixpanel.com"),
)

India Data Residency

Route data to Mixpanel’s India servers by using a custom Consumer with an api_host set to the India domain.

Example Usage

from mixpanel import Mixpanel
 
# use custom consumer with URLs set to Mixpanel's India domain
mp_in = Mixpanel(
  "YOUR_PROJECT_TOKEN",
  consumer=mixpanel.Consumer(api_host="api-in.mixpanel.com"),
)

Disable Geolocation

The Python SDK parse the request IP address to generate geolocation properties for events and profiles. You may want to disable them to prevent the unintentional setting of your data’s geolocation to the location of your server that is sending the request, or to prevent geolocation data from being tracked entirely.

To disable geolocation, set the $ip of your events to 0 and the ip of your profile updates to 0 using the meta argument.

Example Usage

mp = Mixpanel('YOUR_PROJECT_TOKEN')
 
# disable geolocation on events
mp.track('sample_distinct_id','some_event', {
    'some_property': 'some_value'
}, meta={'ip':0})
 
# disable geolocation on profile updates
mp.people_set('sample_distinct_id', {
    'name' : 'sam',
}, meta = {'$ip' : 0}) # do not update geolocation
 

Release History

See all releases.

Was this page useful?