RudderStack Python SDK Reference

Complete Python SDK API reference for tracking and sending server-side events from your Python applications.

RudderStack’s Python SDK provides a comprehensive API for tracking and sending events from your Python applications to various destinations.

For implementation examples and source code, see the SDK’s GitHub repository.

Github Badge

Prerequisites

Installation

To install the RudderStack Python SDK using pip, run the following command:

pip install rudder-sdk-python

Initialization

To initialize the SDK, run the following code snippet:

import rudderstack.analytics as rudder_analytics

rudder_analytics.write_key = WRITE_KEY
rudder_analytics.dataPlaneUrl = DATA_PLANE_URL

Configuration options

The Python SDK provides the following configuration options:

ParameterDescriptionDefault value
on_errorCallback for exception thrown while uploading the messages.None
debugThe SDK prints the logs if set to True.False
sendThe SDK does not send the data to the RudderStack backend if set to False.True
sync_modeThe SDK sends the data immediately instead of queueing it, if set to True.False
max_queue_sizeMaximum queue size the SDK uses to enqueue the events.10000
gzipThe SDK disables gzipping the event data if set to False.True
timeoutThe timeout for sending POST requests to the RudderStack backend.15
max_retriesMaximum number of retry requests the SDK makes to the RudderStack backend.10
upload_intervalMaximum duration between two upload (flush) activities.0.5s
upload_sizeNumber of events in the queue that triggers a flush.100

Event methods

warning
The Python SDK does not persist user state. You must specify either user_id or anonymous_id with every event API call.

Identify

The identify method records user identity and traits.

Example:

rudder_analytics.identify('1hKOmRA4GRlm', {
    'email': 'alex@example.com',
    'name': 'John Doe',
    'friends': 16
})

Parameters:

FieldTypeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for a user in your database.
anonymous_id
Required, if user_id is absent.
StringIdentifier set in cases where no unique user identifier is available.
traitsObjectDictionary of the user’s traits like name, email, etc.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampDatetimeThe timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server.

Track

The track method records user actions and their associated properties.

Method signature:

rudder_analytics.track(user_id=None, anonymous_id=None, event=None, properties=None, context=None, integrations=None, timestamp=None)

Parameters:

FieldTypeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for a user in your database.
anonymous_id
Required, if user_id is absent.
StringIdentifier set in cases where no unique user identifier is available.
event
Required
StringName of the event.
propertiesObjectOptional dictionary of the properties associated with the event.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampDatetimeThe timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server.

Example:

rudder_analytics.track('1hKOmRA4GRlm', 'Article Read', {
    'title': 'The Independence',
    'subtitle': 'Story of the Weak',
    'author': 'John Doe'
})

Page

The page call records page views in your application along with the relevant page information.

Example:

rudder_analytics.page('1hKOmRA4GRlm', 'Documentation', 'Sample Documentation', {
    'url': 'http://rudderstack.com'
})

Parameters:

FieldTypeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for a user in your database.
anonymous_id
Required, if user_id is absent.
StringIdentifier set in cases where no unique user identifier is available.
name
Required
StringName of the viewed page.
category
Required
StringCategory of the viewed page.
propertiesObjectOptional dictionary of the properties associated with the page, like url or referrer.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampDatetimeThe timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server.

Screen

The screen call records screen views in your mobile app.

Example:

rudder_analytics.screen('userid', 'Settings', 'Brightness', {
    'from': 'Settings Screen'
})

Parameters:

FieldTypeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for a user in your database.
anonymous_id
Required, if user_id is absent.
StringIdentifier set in cases where no unique user identifier is available.
name
Required
StringName of the viewed screen.
category
Required
StringCategory of the viewed screen.
propertiesObjectOptional dictionary of the properties associated with the screen, like url or referrer.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampDatetimeThe timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server.

Group

The group call links an identified user with a group and records any custom traits associated with that group.

Example:

rudder_analytics.group('1hKOmRA4GRlm', '12', {
    'name': 'Company',
    'domain': 'IT'
})

Parameters:

FieldTypeDescription
user_id
Required, if anonymous_id is absent.
StringUnique identifier for a user in your database.
anonymous_id
Required, if user_id is absent.
StringIdentifier set in cases where no unique user identifier is available.
group_id
Required
StringUnique identifier for the group in your database.
traitsObjectDictionary of the group’s traits like name or email.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampDatetimeThe timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server.

Alias

warning
RudderStack supports sending alias events only to some destinations. See the destination-specific documentation for more information.

The alias call merges different identities of a known user.

Example:

rudder_analytics.alias('previous_id', 'user_id')

Parameters:

FieldTypeDescription
user_id
Required
StringUnique identifier for a user in your database.
previous_id
Required
StringPrevious identifier for the user.
contextObjectOptional dictionary of information that provides context about the event.
integrationsObjectOptional dictionary containing the destinations to be enabled or disabled.
timestampDatetimeThe timestamp of the event. If not provided, it defaults to the current UTC time. The SDK automatically converts it in the ISO 8601 format before sending to the server.

Event flushing

The Python SDK batches the events and flushes them in the background, for faster and more efficient operation. By default, the SDK flushes a batch of 100 events every 0.5 seconds since the last flush.

You can control the event flushing by tweaking the following parameters:

ParameterDescriptionDefault value
max_queue_sizeMaximum queue size the SDK uses to enqueue the events.10000
upload_intervalMaximum duration between two upload (flush) activities.0.5s

Manual flush

You can also flush the events explicitly by using the SDK’s flush() method to make sure no events are left in the queue.

warning
The SDK blocks the calling thread until all messages are flushed from the queue. Hence, avoid using it as a part of your request lifecycle.

A sample flush call is shown below:

rudder_analytics.flush()

Event request compression

warning
Self-hosted data planes require rudder-server version 1.4+ to support event request compression.

The Python SDK automatically gzips requests. However, you can disable this feature by setting the gzip parameter to false while initializing the SDK:

import rudderstack.analytics as rudder_analytics

rudder_analytics.write_key = WRITE_KEY
rudder_analytics.dataPlaneUrl = DATA_PLANE_URL
rudder_analytics.gzip = False

Error handling

The Python SDK provides a on_error callback that lets you handle any errors that might occur when sending events.

def on_error(error, events):
    print("Error response:", error)

rudder_analytics.on_error = on_error
warning
The on_error callback only returns the errors that occur with the HTTP requests to the RudderStack gateway. It does not return any errors that occur while sending data to your downstream destinations.

The on_error callback function takes the following objects:

ObjectType
errorAPIError type.
eventsList of events that failed while being sent to the RudderStack data plane (backend). It is the raw events data which gets buffered in the SDK. Also, each event contains all the fields included in it.

The below table lists some of the common request responses:

StatusCode
OK200
Request has neither anonymousId nor userId400
Invalid write key401
Invalid JSON400

FAQ

How does the Python SDK handle events larger than 32KB?

The Python SDK drops any events greater than 32KB.

Does the Python SDK support event ordering?

The Python SDK does not support event ordering by default.



Questions? Contact us by email or on Slack