Skip to main content
The PostHog Python SDK enables server-side event tracking, feature flag evaluation, and user identification for Python applications including Django, Flask, FastAPI, and more.

Installation

Install the PostHog Python library using pip:

Initialization

1

Import the library

2

Create a client instance

Initialize PostHog with your project API key and host from your project settings:
3

Verify the connection

Send a test event to verify your setup:
Check your Activity feed to confirm the event was received.
Django Integration: If you’re using Django, check out the Django integration guide for automatic middleware setup and request tracking.

Capturing Events

Basic Event Capture

Capture events with a distinct user ID and optional properties:

Capture with Timestamp

Include a custom timestamp for historical events:

Batch Events

Events are automatically batched for performance. Flush manually when needed:

Identifying Users

Set User Identity

Identify users with their unique ID and properties:

Update User Properties

Set or update properties for existing users:

Set Once

Set properties only if they don’t already exist:

Feature Flags

Check if Flag is Enabled

Get Flag Value

For multivariate flags, get the variant value:

Get Flag Payload

Retrieve JSON payloads attached to feature flags:

Include User Properties

Provide user properties for better flag targeting:

Get All Flags

Retrieve all feature flags for a user:

Group Analytics

Associate users with groups (companies, organizations, etc.):

Alias

Merge user identities when a user transitions from anonymous to identified:

Error Tracking

Capture Exceptions

With Context Manager

Django Integration

For Django applications, use the Django-specific setup:

Flask Integration

FastAPI Integration

Configuration Options

Shutdown

Always flush and close the client when your application shuts down:

Testing

Disable sending events in tests:
Or use a mock:

Best Practices

Use Environment Variables: Store your API key in environment variables, not in code.
Flush on Shutdown: Always call posthog.shutdown() or posthog.flush() before your application exits to ensure all events are sent.
Batch for Performance: The SDK automatically batches events. For high-volume applications, tune max_batch_size and flush_interval.
User Context: Include relevant user properties with identify() to enable better analytics and targeting.

Next Steps

Feature Flags

Learn advanced feature flag techniques

Django Integration

Full Django integration guide

API Reference

Complete Python SDK documentation

Group Analytics

Track B2B metrics by company or organization