references/python.md · 48000
_event_name", distinctId: "user_id", properties: {}, timestamp: new Date("2024-04-03T13:00:00Z") })
await client.shutdown()
## Serverless environments (Render/Lambda/...)
### Synchronous `Posthog`
By default, the synchronous `Posthog` client buffers events before sending them to the capture endpoint. A serverless platform can freeze or terminate the runtime before background delivery finishes.
- For a client shared across invocations, call `posthog.flush()` before the handler returns, including when application code throws. This blocking call attempts to deliver queued events without stopping the client. Its `timeout_seconds` argument defaults to `10` seconds.
- For a disposable client or process exit, call `posthog.shutdown()` after its final work. It attempts to deliver queued events and cleans up the client. Don't reuse the client afterward. Unlike Node's `shutdown()`, Python's `shutdown()` takes no timeout argument.
- Alternatively, enable `sync_mode` when initializing the client so each `posthog.capture()` call attempts delivery before it returns.
These calls do not guarantee that PostHog received every event. If you use [distributed tracing](#distributed-tracing), `sync_mode` doesn't apply to spans. For a shared client, call `posthog.flush()` before the handler returns – see [Shutdown and short-lived processes](#shutdown-and-short-lived-processes).
### Asyncio `AsyncPosthog`
Keep one `AsyncPosthog` client for the lifetime of your application. Use buffered `capture()` by default, or `await capture_immediate()` when one invocation must wait for an event's delivery attempt. Call `await posthog.shutdown()` once during application cleanup. Don't shut down the client after each request.
## Django
See our [Django docs](https://posthog.com/docs/libraries/django.md) for how to set up PostHog in Django. The [Django contexts middleware](https://posthog.com/docs/libraries/django.md#django-contexts-middleware) adds request properties and authenticated user identity to events captured during a request. You can also opt in to browser session and distinct ID headers.
## ASGI request middleware
Version `7.69.0` and later of the Python SDK includes framework-independent ASGI middleware for FastAPI, Starlette, Litestar, and raw ASGI applications. It creates a PostHog context for each HTTP or WebSocket request, enriches captured events with request properties, and captures exceptions that escape the application.
For FastAPI or Starlette, add the middleware to your app:
```python
from fastapi import FastAPI
from posthog import Posthog
from posthog.integrations.asgi import PosthogASGIMiddleware
posthog = Posthog(
"<ph_project_token>",
host="https://us.i.posthog.com",
enable_exception_autocapture=True,
)
app = FastAPI()
app.add_middleware(PosthogASGIMiddleware, client=posthog)
The middleware's capture_exceptions option defaults to None, which inherits the client's enable_exception_autocapture setting. Set it to True or False to override the client. Use request_filter to skip selected requests and extra_properties to add properties from the ASGI scope. Both callbacks can be synchronous or asynchronous.
The middleware ignores X-PostHog-Distinct-ID and X-PostHog-Session-ID by default because clients can control them. Set trust_tracing_headers=True only when you want to accept these headers as analytics context. Don't use them for authentication or authorization.
To instrument another ASGI framework or a raw ASGI app, wrap the application directly:
app = PosthogASGIMiddleware(app, client=posthog)
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.
Supported versions
These docs cover version 7.x of the PostHog Python SDK, which requires Python 3.10 or higher. Python 3.9 is no longer supported on 7.x.x and higher — pin to the 6.x line with pip install 'posthog<7', where 6.9.3 is the final release.
Everything on this page works the same way on 6.9.3. Event capture, the context API (new_context, identify_context, set_context_session), and PosthogContextMiddleware are identical on 6.9.3 and 7.0.0 — 7.0.0 only dropped Python 3.9 and bumped the optional LLM provider SDKs. That includes the middleware identifying the request context from the X-POSTHOG-DISTINCT-ID header and falling back to the authenticated user, which behaves the same across both lines.
Later 7.x releases add what the 6.x line does not receive, such as the Celery integration, tracing header sanitization, and set_context_device_id. They also changed the middleware's own captured properties: 7.x sends the request IP as $ip, where 6.9.3 sends it as $ip_address, and 7.x additionally captures $request_path, $raw_user_agent, and the authenticated user's email.