Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 74 additions & 1 deletion bin/docs_scripts/generate_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
types.FeatureFlag types.FlagsAndPayloads types.UnresolvedFlagReason feature_flags.InconclusiveMatchError
feature_flags.RequiresServerEvaluation capture_send.CaptureError tracing.span.Span emails.Emails
emails.EmailError emails.SendEmailResult args.OptionalSetArgs emails.CodeEmailArgs""".split()
UTILS = """integrations.django.PosthogContextMiddleware integrations.flask.PosthogFlaskIntegration
UTILS = """integrations.django.PosthogContextMiddleware integrations.drf.exception_handler
integrations.drf.create_exception_handler integrations.flask.PosthogFlaskIntegration
integrations.asgi.PosthogASGIMiddleware integrations.celery.PosthogCeleryIntegration
request.set_socket_options request.enable_keep_alive request.disable_connection_reuse""".split()
FIRST = ["setup", "capture", "identify"]
Expand Down Expand Up @@ -86,6 +87,74 @@ def section(objects, **kwargs):
)


def fold_parameter_tables(md: str) -> str:
"""Fold 4-column parameter tables into 2 columns (Name | Description)."""
out, in_params = [], False
for line in md.splitlines():
if line == "Name | Type | Description | Default":
out.append("Name | Description")
in_params = True
continue
if in_params:
if line.startswith("---- |"):
out.append("---- | -----------")
continue
if not line.strip() or not line.startswith("`"):
in_params = False
else:
parts = re.split(r"(?<!\\) \| ", line)
if len(parts) == 4:
name, typ, desc, default = (p.strip() for p in parts)
cells = []
if typ:
cells.append(f"{typ}.")
if desc:
if default and desc[-1] not in ".!?:":
desc += "."
cells.append(desc)
if default == "*required*":
cells.append("Required.")
elif default:
cells.append(f"Default: {default}.")
out.append(f"{name} | {' '.join(cells)}")
continue
out.append(line)
return "\n".join(out)


def unwrap_prose(md: str) -> str:
"""Join hard-wrapped lines inside prose paragraphs and bullet items."""
out, in_fence = [], False
for line in md.splitlines():
if line.lstrip().startswith("```"):
in_fence = not in_fence
out.append(line)
continue
if in_fence:
out.append(line)
continue
stripped = line.strip()
is_special = (
not stripped
or stripped.startswith(("#", "|", "<", "**", "Bases:", "----"))
or " | " in line
or bool(re.match(r"^(?:[-*]|\d+\.) ", stripped))
)
prev = out[-1] if out else ""
prev_stripped = prev.strip()
prev_is_joinable = (
bool(prev_stripped)
and not prev_stripped.startswith(("#", "|", "<", "**", "Bases:", "----"))
and " | " not in prev
and not prev.lstrip().startswith("```")
)
if not is_special and prev_is_joinable:
out[-1] = f"{prev.rstrip()} {stripped}"
else:
out.append(line)
return "\n".join(out)


def entry(obj, name: str) -> str:
template = ENV.get_template(f"{obj.kind.value}.md.jinja")
md = template.render(**griffe2md.prepare_context(obj, CONFIG))
Expand All @@ -95,6 +164,10 @@ def entry(obj, name: str) -> str:
md = re.sub(r"<code>(.*?)</code>", r"`\1`", md.replace("<br>", "<br />"))
# A parameter documented only in the docstring, like a **kwargs key, isn't required.
md = re.sub(r"^(`\w+` \| \| .*) \| \*required\*$", r"\1 | ", md, flags=re.M)
# An unannotated function's Returns row starts with " | ", which GFM shifts into Type.
md = re.sub(r"(Type \| Description\n---- \| -----------\n) \| ", r"\1- | ", md)
md = fold_parameter_tables(md)
md = unwrap_prose(md)
return re.sub(r"^### .*$", f"### `{name}`", md.strip(), count=1, flags=re.M)


Expand Down
17 changes: 17 additions & 0 deletions docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@ posthog.capture("user_signed_up", distinct_id="user_123", properties={"plan": "f

`capture` queues the event and returns right away. A background thread sends it.

## Share context across calls

Open a context with `new_context()` or `@scoped()`. Every event, exception, flag evaluation, and span inside shares the same user ID, session ID, and tags.

```python
with posthog.new_context():
posthog.identify_context("user_123")
posthog.tag("plan", "pro")
posthog.capture("checkout_started")
```

- **Open a context first.** `identify_context()`, `tag()`, and `set_context_*()` silently do nothing outside `new_context()` or `@scoped()`.
- **Isolate requests and jobs.** Pass `fresh=True` at request or worker boundaries, so parent state doesn't leak. For web apps, use `PosthogASGIMiddleware` (FastAPI, Starlette, ASGI) or `PosthogContextMiddleware` (Django).
- **Use with `AsyncPosthog`.** Contexts live in `contextvars`, so `from posthog import new_context, identify_context, tag` and `PosthogASGIMiddleware` apply to `AsyncPosthog` calls too.

## Shut down

Call `shutdown()` before your process exits, so queued events are sent.
Expand All @@ -47,6 +62,7 @@ from contextlib import asynccontextmanager

from fastapi import FastAPI
from posthog import AsyncPosthog
from posthog.integrations.asgi import PosthogASGIMiddleware

@asynccontextmanager
async def lifespan(app: FastAPI):
Expand All @@ -55,6 +71,7 @@ async def lifespan(app: FastAPI):
yield

app = FastAPI(lifespan=lifespan)
app.add_middleware(PosthogASGIMiddleware)
```

## The posthoganalytics package
Expand Down
42 changes: 33 additions & 9 deletions posthog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,16 @@ def new_context(
"""
Create a new context scope that will be active for the duration of the with block.

Contexts store shared identity, session ID, options, and tags in ``contextvars``:

- **Scope required.** ``identify_context()``, ``tag()``, and ``set_context_*()`` silently do nothing outside ``new_context()`` or ``@scoped()``.
- **Propagation.** State carries across function calls and ``await`` automatically. New threads start with an empty context.
- **Inheritance.** Child contexts inherit parent values without mutating the parent. Pass ``fresh=True`` at request or job boundaries to clear inherited state.
- **Precedence.** Explicit arguments on ``capture()`` override context state, and context state overrides ``super_properties``.

Args:
fresh: Whether to start with a fresh context (default: False)
capture_exceptions: Whether to capture exceptions raised within the context. If omitted, defaults to the relevant client's exception autocapture setting.
capture_exceptions: Whether to capture uncaught exceptions escaping the ``with`` block. If omitted, defaults to the relevant client's exception autocapture setting.
client: Optional Posthog client instance to use for this context (default: None)

Examples:
Expand All @@ -135,6 +142,9 @@ def scoped(fresh=False, capture_exceptions: Optional[bool] = None):
"""
Decorator that creates a new context for the function.

Works on both sync and ``async def`` functions. Put ``scoped`` closest to
the function when stacking decorators.

Args:
fresh: Whether to start with a fresh context (default: False)
capture_exceptions: Whether to capture and track exceptions with posthog error tracking. If omitted, defaults to the global exception autocapture setting.
Expand All @@ -158,13 +168,18 @@ def set_context_session(session_id: str):
"""
Set the session ID for the current context.

Session IDs must be valid UUIDv7 strings. Forward PostHog JS's ``X-POSTHOG-SESSION-ID`` header here to link backend events to Session Replay.

Call this inside ``new_context()`` or ``@scoped()``. Calls outside a context do nothing.

Args:
session_id: The session ID to associate with the current context and its children

Examples:
```python
from posthog import set_context_session
set_context_session("session_123")
from posthog import new_context, set_context_session
with new_context():
set_context_session("session_123")
```

Category:
Expand All @@ -178,13 +193,16 @@ def set_context_device_id(device_id: str):
Set the device ID for the current context, associating all feature flag requests
in this or child contexts with the given device ID.

Call this inside ``new_context()`` or ``@scoped()``. Calls outside a context do nothing.

Args:
device_id: The device ID to associate with the current context and its children

Examples:
```python
from posthog import set_context_device_id
set_context_device_id("device_123")
from posthog import new_context, set_context_device_id
with new_context():
set_context_device_id("device_123")
```

Category:
Expand All @@ -197,13 +215,16 @@ def identify_context(distinct_id: str):
"""
Identify the current context with a distinct ID.

Call this inside ``new_context()`` or ``@scoped()``. Calls outside a context do nothing.

Args:
distinct_id: The distinct ID to associate with the current context and its children

Examples:
```python
from posthog import identify_context
identify_context("user_123")
from posthog import new_context, identify_context
with new_context():
identify_context("user_123")
```

Category:
Expand Down Expand Up @@ -278,14 +299,17 @@ def tag(name: str, value: Any):
"""
Add a tag to the current context.

Call this inside ``new_context()`` or ``@scoped()``. Calls outside a context do nothing.

Args:
name: The tag key
value: The tag value

Examples:
```python
from posthog import tag
tag("user_id", "123")
from posthog import new_context, tag
with new_context():
tag("plan", "pro")
```

Category:
Expand Down
77 changes: 69 additions & 8 deletions posthog/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,30 @@ def __init__(
email_request_max_retries: int = 2,
migrated_from: Optional[str] = None,
) -> None:
"""Create an async PostHog client. Import it as ``AsyncPosthog`` from ``posthog``.

Keep one client for your app's lifetime on one event loop. Open it with
``async with AsyncPosthog(...)``, or call ``await shutdown()`` on teardown.

#### Know what to await

Queue methods write to memory and return right away. Network reads and lifecycle calls are coroutines.

| Call | Methods | Reach for it when |
| --- | --- | --- |
| Don't ``await`` | ``capture``, ``capture_ai``, ``set``, ``set_once``, ``group_identify``, ``alias``, ``capture_exception`` | Queueing events on the request path without waiting on HTTP |
| ``await`` | ``capture_immediate``, ``capture_ai_immediate`` | A handler must confirm the upload attempt finished before returning |
| ``await`` | ``evaluate_flags``, ``get_remote_config_payload``, ``emails.send``, ``emails.get``, ``flush``, ``shutdown``, ``join`` | Evaluating flags, sending emails, or draining queues on the event loop |

#### The differences from ``Client``

Shared constructor options behave the same as on ``Client(...)``, with these differences:

- **Remote flags only.** ``secret_key`` authenticates ``get_remote_config_payload()`` and ``emails``. ``AsyncPosthog`` doesn't poll flag definitions locally, so ``enable_local_evaluation``, ``poll_interval``, ``flag_definition_cache_provider``, and ``flag_fallback_cache_url`` aren't accepted.
- **Async callbacks.** ``before_send`` and ``on_error`` accept regular functions or ``async def`` coroutines.
- **Shared contexts.** ``AsyncPosthog`` has no context methods. Open a context with ``posthog.new_context()``, ``posthog.scoped()``, or ``PosthogASGIMiddleware``, then call ``posthog.identify_context()`` and ``posthog.tag()`` inside it.
- **Client-only options and methods.** ``sync_mode``, ``start_span()``, ``metrics``, ``traces``, ``enable_exception_autocapture``, ``enable_exception_autocapture_rate_limiting``, and the ``exception_autocapture_*`` rate-limit options live on sync ``Posthog`` only and raise ``TypeError`` if passed here.
"""
if flush_at <= 0:
raise ValueError("flush_at must be greater than zero")
if flush_interval <= 0:
Expand Down Expand Up @@ -360,14 +384,13 @@ def __init__(
@property
def emails(self) -> AsyncEmails:
"""
Send transactional email from PostHog email templates or from content
in your code, and read the status of each email sent with ``get``.
Send transactional email from PostHog templates or inline code, and read
delivery status with ``get``.

Needs ``secret_key``, a project secret API key with the ``transactional_email:write``
scope, and ``posthog[async]``. Sends go to ``app_host``, or to the PostHog
Cloud app host of ``host``. ``email_request_timeout_seconds`` and
``email_request_max_retries`` configure each send. A disabled or shut-down
client sends nothing. See ``posthog.emails`` for setup.
- **Requirements.** Needs ``posthog[async]`` and a ``secret_key`` project secret API key with the ``transactional_email:write`` scope.
- **Routing.** Sends go to ``app_host``, or to the PostHog Cloud app host of ``host``.
- **Retries and timeouts.** Configured by ``email_request_timeout_seconds`` and ``email_request_max_retries``.
- **Lifecycle.** A disabled or shut-down client sends nothing. See ``posthog.emails`` for full setup.

Examples:
```python
Expand Down Expand Up @@ -700,7 +723,11 @@ def _build_capture_event(
def capture(
self, event: str, **kwargs: Unpack[OptionalCaptureArgs]
) -> Optional[str]:
"""Queue an event without blocking for network delivery."""
"""Queue an event without blocking for network delivery.

Don't ``await`` this method. Call ``await capture_immediate()`` to wait for
delivery, or see ``Client.capture`` for parameter rules.
"""
return self._capture(event, self._analytics_lane, kwargs)

def capture_ai(
Expand Down Expand Up @@ -846,6 +873,13 @@ def _build_person_properties_event(
}

def set(self, **kwargs: Unpack[OptionalSetArgs]) -> Optional[str]:
"""Queue a ``$set`` event to overwrite person properties.

Don't ``await`` this method, which uses ``identify_context()`` when
``distinct_id`` is omitted and folds active tags into ``$set``. Without a
distinct ID (explicit or from ``identify_context()``), it sends nothing
and returns ``None``.
"""
try:
msg = self._build_person_properties_event("$set", "$set", kwargs)
if msg is None:
Expand All @@ -860,6 +894,11 @@ def set(self, **kwargs: Unpack[OptionalSetArgs]) -> Optional[str]:
return None

def set_once(self, **kwargs: Unpack[OptionalSetArgs]) -> Optional[str]:
"""Queue a ``$set_once`` event to set person properties only when unset.

Don't ``await`` this method. It follows the same context and tag rules as
``set()`` without overwriting existing values.
"""
try:
msg = self._build_person_properties_event("$set_once", "$set_once", kwargs)
if msg is None:
Expand All @@ -884,6 +923,12 @@ def group_identify(
distinct_id: Optional[ID_TYPES] = None,
options: Optional[Dict[str, Any]] = None,
) -> Optional[str]:
"""Queue a ``$groupidentify`` event to update group properties.

Don't ``await`` this method, which requires the Group Analytics add-on. Pass
``name`` in ``properties`` for the UI display name, and pass ``groups`` on
``capture()`` to link events.
"""
try:
if not _stringify_id(group_type):
self.log.warning(
Expand Down Expand Up @@ -934,6 +979,11 @@ def alias(
disable_geoip: Optional[bool] = None,
options: Optional[Dict[str, Any]] = None,
) -> Optional[str]:
"""Queue a ``$create_alias`` event linking ``previous_id`` to ``distinct_id``.

Don't ``await`` this method. Neither ID falls back to ``identify_context()``,
and you shouldn't alias users to a shared placeholder like ``"anonymous"``.
"""
try:
resolved_previous_id = _stringify_id(previous_id)
if not resolved_previous_id:
Expand Down Expand Up @@ -1383,6 +1433,11 @@ async def wait_for_workers() -> None:
await asyncio.gather(queue_join, workers_finished, return_exceptions=True)

async def flush(self, timeout_seconds: Optional[float] = 10) -> None:
"""Drain queued analytics and AI events while keeping the client open.

Await this before a short-lived handler returns rather than calling
``shutdown()`` per request.
"""
if asyncio.current_task() in self._all_worker_tasks() or _is_processing_event():
self._defer_lifecycle_call(self.flush(timeout_seconds))
return
Expand Down Expand Up @@ -1419,6 +1474,11 @@ async def _close_transport(self) -> None:
await http_client.aclose()

async def shutdown(self) -> None:
"""Flush queued events, stop async workers, and close HTTP transports.

Await this once at app teardown, or use ``async with AsyncPosthog(...)``.
Don't reuse the client afterward.
"""
current = asyncio.current_task()
if (
current in self._all_worker_tasks()
Expand Down Expand Up @@ -1492,6 +1552,7 @@ async def shutdown(self) -> None:
raise errors[0]

async def join(self) -> None:
"""Alias for ``await shutdown()``."""
await self.shutdown()


Expand Down
Loading