Python Library

Last updated:

This is the official PostHog library for Python to capture and send events to any PostHog instance.

View on GitHub

This is an optional library you can install if you're working with Python. It uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your web app or other server side application that needs performance.


pip install posthog

In your app, import the posthog library and set your api key and host before making any calls.

import posthog
# Substitutes posthog.api_key which still exists but has been deprecated
posthog.project_api_key = '<ph_project_api_key>'
# Only necessary if you want to use feature flags
posthog.personal_api_key = '<ph_personal_api_key>'
# You can remove this line if you're using = '<ph_instance_address>'

You can read more about the differences between the project and personal API keys in the dedicated API authentication section of the Docs.

Note: As a general rule of thumb, we do not recommend having API keys in plaintext. Setting it as an environment variable would be best.

You can find your keys in the 'Project Settings' page in PostHog.

To debug, you can toggle debug mode on:

posthog.debug = True

And to make sure no calls happen during your tests, you can disable them, like so:

if settings.TEST:
posthog.disabled = True

Making Calls


Capture allows you to capture anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve or where people are giving up.

A capture call requires:

  • distinct id which uniquely identifies your user
  • event name to specify the event
  • We recommend naming events with "[noun][verb]", such as movie played or movie updated, in order to easily identify what your events mean later on (we know this from experience).

Optionally you can submit:

  • properties, which is a dictionary with any information you'd like to add
  • timestamp, a datetime object for when the event happened. If this isn't submitted, it'll be set to the current time
  • uuid, a unique uuid for the event, leave blank to autogenerate

For example:

posthog.capture('distinct id', 'movie played', {'movie_id': '123', 'category': 'romcom'})


posthog.capture('distinct id', event='movie played', properties={'movie_id': '123', 'category': 'romcom'}, timestamp=datetime.utcnow().replace(tzinfo=tzutc()))

Setting user properties via an event

To set properties on your users via an event, you can leverage the event properties $set and $set_once.



'distinct id',
event='movie played',
properties={ '$set': { 'userProperty': 'value' } }


When capturing an event, you can pass a property called $set as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.



'distinct id',
event='movie played',
properties={ '$set_once': { 'userProperty': 'value' } }


$set_once works just like $set, except that it will only set the property if the user doesn't already have that property set.


We highly recommend reading our section on Identifying users to better understand how to correctly use this method.

Identify lets you add metadata to your users so you can easily identify who they are in PostHog, as well as do things like segment users by these properties.

An identify call requires:

  • distinct id which uniquely identifies your user
  • properties with a dict with any key:value pairs

For example:

posthog.identify('distinct id', {
'email': '[email protected]',
'name': 'Dwayne Johnson'

The most obvious place to make this call is whenever a user signs up, or when they update their information.


To connect whatever a user does before they sign up or log in with what they do after you need to make an alias call. This will allow you to answer questions like "Which marketing channels leads to users churning after a month?" or "What do users do on our website before signing up?"

In a purely back-end implementation, this means whenever an anonymous user does something, you'll want to send a session ID (Django, Flask) with the capture call. Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.

The same concept applies for when a user logs in.

If you're using PostHog in the front-end and back-end, doing the identify call in the frontend will be enough.

An alias call requires:

  • previous distinct id the unique ID of the user before
  • distinct id the current unique id

For example:

posthog.alias('anonymous session id', 'distinct id')

Feature flags

Note: To use feature flags you must also set a personal_api_key when configuring the integration, as described in the Installation section.

PostHog's Feature Flags allow you to safely deploy and roll back new features.

When using them with one of libraries, you should check if a feature flag is enabled and use the result to toggle functionality on and off in you application.

How to check if a flag is enabled

posthog.feature_enabled('beta-feature', 'distinct id')

Example use case

Here's how you might send different users a different version of your homepage, for example:

def homepage(request):
template = "new.html" if posthog.feature_enabled('new_ui', 'distinct id') else "old.html"
return render_template(template, request=request)

Note: Feature flags are persistent for users across sessions. Read more about feature flag persistence on our dedicated page.

Sending page views

If you're aiming for a full back-end implementation of PostHog, you can send pageviews from your backend

posthog.capture('distinct id', '$pageview', {'$current_url': ''})


For Django, you can do the initialisation of the key in the AppConfig, so that it's available everywhere.

in yourapp/

from django.apps import AppConfig
import posthog
class YourAppConfig(AppConfig):
def ready(self):
posthog.api_key = '<ph_project_api_key>' = '<ph_instance_address>' # You can remove this line if you're using

Then, anywhere else in your app you can do:

import posthog
def purchase(request):
# example capture
posthog.capture(, 'purchase', ...)



When using Sentry in Python, you can connect to PostHog in order to link Sentry errors to PostHog user profiles.

Example implementation

See the sentry_django_example project for a complete example.

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from posthog.sentry.posthog_integration import PostHogIntegration
PostHogIntegration.organization = "orgname"
dsn="https://[email protected]/0",
integrations=[DjangoIntegration(), PostHogIntegration()],
# Also set `posthog_distinct_id` tag
from sentry_sdk import configure_scope
with configure_scope() as scope:
scope.set_tag('posthog_distinct_id', 'some distinct id')

Example implementation with Django

This can be made automatic in Django, by adding the following middleware and settings to

"distinct_id": lambda request: request.user and request.user.distinct_id

Alternative name

As our open source project PostHog shares the same module name, we created a special posthoganalytics package, mostly for internal use to avoid module collision. It is the exact same.

Thank you

This library is largely based on the analytics-python package.