From 55a29c77863ecff5b1d30b126030858d7953fb00 Mon Sep 17 00:00:00 2001 From: "wizard-ci-bot[bot]" <254716194+wizard-ci-bot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 22:13:04 +0000 Subject: [PATCH] wizard-ci: fastapi/fastapi3-ai-saas --- .../integration-fastapi/.posthog-wizard | 0 .../references/identify-users.md | 307 +++++ .../integration-fastapi/references/python.md | 1024 +++++++++++++++++ .../fastapi/fastapi3-ai-saas/.env.example | 4 + .../fastapi/fastapi3-ai-saas/app/config.py | 4 + .../fastapi/fastapi3-ai-saas/app/main.py | 30 + .../fastapi3-ai-saas/app/middleware.py | 65 +- .../fastapi3-ai-saas/app/routers/api_keys.py | 7 + .../fastapi3-ai-saas/app/routers/auth.py | 25 +- .../fastapi3-ai-saas/app/routers/generate.py | 11 + .../fastapi3-ai-saas/app/routers/settings.py | 12 +- .../fastapi/fastapi3-ai-saas/requirements.txt | 1 + 12 files changed, 1482 insertions(+), 8 deletions(-) create mode 100644 apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/.posthog-wizard create mode 100644 apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/references/identify-users.md create mode 100644 apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/references/python.md diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/.posthog-wizard b/apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/references/identify-users.md b/apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/references/identify-users.md new file mode 100644 index 000000000..8647dcb37 --- /dev/null +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/references/identify-users.md @@ -0,0 +1,307 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Identify users - Docs + +Copy page + +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/usage.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/usage.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +#### Identify users when the web SDK loads + +If your app already knows the signed-in user when you initialize the JavaScript web SDK, the [`loaded` callback](/docs/libraries/js/config.md) is a convenient place to call `identify`. This identifies the user as soon as the SDK has loaded: + +Web + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + loaded: (posthog) => { + if (currentUser?.id) { + posthog.identify(currentUser.id, { + email: currentUser.email, + name: currentUser.name, + }) + } + }, +}) +``` + +In this example, `currentUser` represents user data already available from your authentication system. If your app loads the user asynchronously, call `posthog.identify()` as soon as that data becomes available instead. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +**\`$set\` and \`$set\_once\` aren't stored on events** + +These properties only tell PostHog how to update person data during ingestion — they aren't kept on the stored event, so you can't filter, break down, or query events by them. To query the values you set, use [person properties](/docs/product-analytics/person-properties.md) instead. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/usage.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/usage.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/references/python.md b/apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/references/python.md new file mode 100644 index 000000000..85b12cf37 --- /dev/null +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/.claude/skills/integration-fastapi/references/python.md @@ -0,0 +1,1024 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Python - Docs + +Copy page + +# Python - Docs + +The Python SDK makes it easy to capture events, evaluate feature flags, track errors, and more in your Python apps. + +> These docs cover version `7.x` of the Python SDK, which requires Python 3.10 or higher. On Python 3.9? See [supported versions](#supported-versions). + +## Installation + +Terminal + +PostHog AI + +```bash +pip install posthog +``` + +**Upgrading to v6** + +Version `6.x` of the PostHog Python SDK introduces a new [contexts](/docs/libraries/python.md#contexts) API and breaking changes. If you're upgrading from `5.x` to `6.x`, read the [migration guide](/tutorials/python-v6-migration.md) first to learn more. + +In your app, import the `posthog` library and set your project token and host **before** making any calls. + +Python + +PostHog AI + +```python +from posthog import Posthog +posthog = Posthog('', host='https://us.i.posthog.com') +``` + +> **Note:** As a rule of thumb, we do not recommend having API keys or tokens in plaintext. Setting it as an environment variable is best. + +You can find your project token and instance address in the [project settings](https://app.posthog.com/project/settings) page in PostHog. + +## Use the asyncio client + +The Python SDK includes an asyncio-native client in version `7.45.0` and later. Continue to use `Posthog` in synchronous apps. For an asyncio app, install the optional async dependencies: + +Terminal + +PostHog AI + +```bash +pip install "posthog[async]>=7.45.0" +``` + +Import `AsyncPosthog`, the customer-facing name for `AsyncClient`. Both names provide the same async context manager and lifecycle methods. Keep one client for the lifetime of your app. For example, use a FastAPI lifespan handler: + +Python + +PostHog AI + +```python +import os +from contextlib import asynccontextmanager +from fastapi import FastAPI +from posthog import AsyncPosthog +@asynccontextmanager +async def lifespan(app: FastAPI): + async with AsyncPosthog( + os.environ["POSTHOG_PROJECT_TOKEN"], + host=os.environ["POSTHOG_HOST"], + secret_key=os.environ.get("POSTHOG_FEATURE_FLAGS_SECURE_API_KEY"), + ) as posthog: + app.state.posthog = posthog + yield +app = FastAPI(lifespan=lifespan) +``` + +Exiting the context calls `shutdown()`. This flushes buffered events, waits for in-flight operations, stops the workers, and closes the HTTP transport. If you don't use the context manager, call `await posthog.shutdown()` during app shutdown. `await posthog.join()` has the same effect. + +### Capture events without blocking the event loop + +`capture()` queues an event and returns without waiting for a network request. Don't await it: + +Python + +PostHog AI + +```python +posthog.capture( + "event_name", + distinct_id="user-distinct-id", + properties={"source": "fastapi"}, +) +``` + +Use `capture_immediate()` when your code must wait for that event's delivery attempt: + +Python + +PostHog AI + +```python +capture_id = await posthog.capture_immediate( + "event_name", + distinct_id="user-distinct-id", +) +``` + +### Evaluate feature flags + +Await `evaluate_flags()` once, then use its snapshot with synchronous in-memory accessors. Pass the same snapshot to `capture()` to attach the exact values used for branching without another feature flag request: + +Python + +PostHog AI + +```python +flags = await posthog.evaluate_flags("user-distinct-id") +if flags.is_enabled("new-checkout"): + # Show the new checkout + pass +posthog.capture( + "checkout started", + distinct_id="user-distinct-id", + flags=flags, +) +``` + +The snapshot provides synchronous `is_enabled()`, `get_flag()`, and `get_flag_payload()` accessors. The awaited `evaluate_flags()` call also accepts `groups`, `person_properties`, `group_properties`, `disable_geoip`, `flag_keys`, and `device_id` arguments. + +### Fetch remote config + +Initialize the client with a server-side [feature flags secure API key](/docs/feature-flags/remote-config.md#step-1-find-your-feature-flags-secure-api-key) as `secret_key`, then await the remote config request: + +Python + +PostHog AI + +```python +config = await posthog.get_remote_config_payload("landing-page-config") +``` + +See [Remote config](/docs/feature-flags/remote-config.md) for setup and security details. + +## Identifying users + +> **Identifying users is required.** Backend events need a `distinct_id` to associate events with the correct user. +> +> In Python, you can do this through a context. All event captures in the same context will be tagged automatically with the correct `distinct_id`. Typically, you would set a fresh context and identify at the top of each route. +> +> Python +> +> PostHog AI +> +> ```python +> from posthog import new_context, identify_context, capture +> @app.get("/foo") +> def foo(current_user: User = Depends(get_current_user)): +> with new_context(): # Set context at the top of a route +> identify_context(current_user.id) +> capture("foo_viewed") +> return {"status": "ok"} +> ``` +> +> When possible, write a small piece of **middleware** that resolves your authenticated user, wrap a context around the request, and identifies it. Every `capture()` downstream is then attributed *automatically*. The SDK's Django middleware does this automatically and you can replicate it when using the plain Python SDK. + +## Capturing events + +You can send custom events using `capture`: + +Python + +PostHog AI + +```python +# Events captured with no context or explicit distinct_id are marked as personless and have an auto-generated distinct_id: +posthog.capture('some-anon-event') +from posthog import identify_context, new_context +# Use contexts to manage user identification across multiple capture calls +with new_context(): + identify_context('distinct_id_of_the_user') + posthog.capture('user_signed_up') + posthog.capture('user_logged_in') + # You can also capture events with a specific distinct_id + posthog.capture('some-custom-action', distinct_id='distinct_id_of_the_user') +``` + +> **Tip:** We recommend using a `[object] [verb]` format for your event names, where `[object]` is the entity that the behavior relates to, and `[verb]` is the behavior itself. For example, `project created`, `user signed up`, or `invite sent`. + +> **Tip:** You can define event schemas with typed properties and generate type-safe code using [schema management](/docs/product-analytics/schema-management.md). + +### Setting event properties + +Optionally, you can include additional information with the event by including a [properties](/docs/data/events.md#event-properties) object: + +Python + +PostHog AI + +```python +posthog.capture( + "user_signed_up", + distinct_id="distinct_id_of_the_user", + properties={ + "login_type": "email", + "is_free_trial": "true" + } +) +``` + +### Sending page views + +If you're aiming for a backend-only implementation of PostHog and won't be capturing events from your frontend, you can send `pageviews` from your backend like so: + +Python + +PostHog AI + +```python +posthog.capture('$pageview', distinct_id="distinct_id_of_the_user", properties={'$current_url': 'https://example.com'}) +``` + +## Person profiles and properties + +The Python SDK captures identified events if the current context is identified or if you pass a distinct ID explicitly. These create [person profiles](/docs/data/persons.md). To set [person properties](/docs/product-analytics/person-properties.md) in these profiles, include them when capturing an event: + +Python + +PostHog AI + +```python +# Passing a distinct id explicitly +posthog.capture( + 'event_name', + distinct_id='user-distinct-id', + properties={ + '$set': {'name': 'Max Hedgehog'}, + '$set_once': {'initial_url': '/blog'} + } +) +# Using contexts +from posthog import new_context, identify_context +with new_context(): + identify_context('user-distinct-id') + posthog.capture('event_name') +``` + +For more details on the difference between `$set` and `$set_once`, see our [person properties docs](/docs/product-analytics/person-properties.md#what-is-the-difference-between-set-and-set_once). + +To capture [anonymous events](/docs/data/anonymous-vs-identified-events.md) without person profiles, set the event's `$process_person_profile` property to `False`. Events captured with no context or explicit distinct\_id are marked as personless, and will have an auto-generated distinct\_id: + +Python + +PostHog AI + +```python +posthog.capture( + event='event_name', + properties={ + '$process_person_profile': False + } +) +``` + +## Alias + +Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend. + +In this case, you can use `alias` to assign another distinct ID to the same user. + +Python + +PostHog AI + +```python +posthog.alias(previous_id='distinct_id', distinct_id='alias_id') +``` + +We strongly recommend reading our docs on [alias](/docs/product-analytics/identify.md#alias-assigning-multiple-distinct-ids-to-the-same-user) to best understand how to correctly use this method. + +## Contexts + +The Python SDK uses nested contexts for managing state that's shared across events. Contexts are the recommended way to manage things like "which user is taking this action" (through `identify_context`), rather than manually passing user state through your apps stack. + +When events (including exceptions) are captured in a context, the event uses the user [distinct ID](/docs/getting-started/identify-users.md), [session ID](/docs/data/sessions.md), and tags that are (optionally) set in the context. This is useful for adding properties to multiple events during a single user's interaction with your product. + +You can enter a context using the `with` statement: + +Python + +PostHog AI + +```python +from posthog import new_context, tag, set_context_session, identify_context +with new_context(): + tag("transaction_id", "abc123") + tag("some_arbitrary_value", {"tags": "can be dicts"}) + # Sessions are UUIDv7 values and used to track a sequence of events that occur within a single user session + # See https://posthog.com/docs/data/sessions + set_context_session(session_id) + # Setting the context-level distinct ID. See below for more details. + identify_context(user_id) + # This event is captured with the distinct ID, session ID, and tags set above + posthog.capture("order_processed") +``` + +Contexts are persisted across function calls. If you enter one and then call a function and capture an event in the called function, it uses the context tags and session ID set in the parent context: + +Python + +PostHog AI + +```python +from posthog import new_context, tag +def some_function(): + # When called from `outer_function`, this event is captured with the property some-key="value-4" + posthog.capture("order_processed") +def outer_function(): + with new_context(): + tag("some-key", "value-4") + some_function() +``` + +Contexts are nested, so tags added to a parent context are inherited by child contexts. If you set the same tag in both a parent and child context, the child context's value overrides the parent's at event capture (but the parent context won't be affected). This nesting also applies to session IDs and distinct IDs. + +Python + +PostHog AI + +```python +from posthog import new_context, tag +with new_context(): + tag("some-key", "value-1") + tag("some-other-key", "another-value") + with new_context(): + tag("some-key", "value-2") + # This event is captured with some-key="value-2" and some-other-key="another-value" + posthog.capture("order_processed") + # This event is captured with some-key="value-1" and some-other-key="another-value" + posthog.capture("order_processed") +``` + +You can disable this nesting behavior by passing `fresh=True` to `new_context`: + +Python + +PostHog AI + +```python +from posthog import new_context, tag +with new_context(fresh=True): + tag("some-key", "value-2") + # This event only has the property some-key="value-2" from the fresh context + posthog.capture("order_processed") +``` + +> **Note:** Distinct IDs, session IDs, and properties passed directly to calls to `capture` and related functions override context state in the final event captured. + +### Contexts and user identification + +Contexts can be associated with a distinct ID by calling `posthog.identify_context`: + +Python + +PostHog AI + +```python +from posthog import identify_context +identify_context("distinct-id") +``` + +Within a context associated with a distinct ID, all events captured are associated with that user. You can override the distinct ID for a specific event by passing a `distinct_id` argument to `capture`: + +Python + +PostHog AI + +```python +from posthog import new_context, identify_context +with new_context(): + identify_context("distinct-id") + posthog.capture("order_processed") # will be associated with distinct-id + posthog.capture("order_processed", distinct_id="another-distinct-id") # will be associated with another-distinct-id +``` + +It's recommended to pass the currently active distinct ID from the frontend to the backend, using the `X-POSTHOG-DISTINCT-ID` header. If you're using our Django middleware, this is extracted and associated with the request handler context automatically. + +You can read more about identifying users in the [user identification documentation](/docs/product-analytics/identify.md). + +### Contexts and sessions + +Contexts can be associated with a session ID by calling `posthog.set_context_session`. When linking backend events to frontend sessions, use the session ID from the frontend SDK (PostHog session IDs are UUIDv7 strings). + +Python + +PostHog AI + +```python +from posthog import new_context, set_context_session +with new_context(): + set_context_session(request.get_header("X-POSTHOG-SESSION-ID")) +``` + +**Using PostHog on your frontend too?** + +If you're using the PostHog JavaScript Web SDK on your frontend, it generates a session ID for you. Configure [`tracing_headers`](/docs/libraries/js/config.md#tracing-headers) for your backend hostname to add the session and distinct ID headers to browser requests automatically. + +You need to extract the header in your request handler (if you're using our Django middleware integration, this happens automatically). + +If you associate a context with a session, you'll be able to do things like: + +- See backend events on the session timeline when viewing session replays +- View session replays for users that triggered a backend exception in error tracking + +You can read more about sessions in the [session tracking](/docs/data/sessions.md) documentation. + +### Exception capture + +By default exceptions raised within a context are captured and available in the [error tracking](/docs/error-tracking.md) dashboard. You can override this behavior by passing `capture_exceptions=False` to `new_context`: + +Python + +PostHog AI + +```python +from posthog import new_context, tag +with new_context(capture_exceptions=False): + tag("transaction_id", "abc123") + tag("some_arbitrary_value", {"tags": "can be dicts"}) + # This event will be captured with the tags set above + posthog.capture("order_processed") + # This exception will not be captured + raise Exception("Order processing failed") +``` + +### Decorating functions + +The SDK exposes a function decorator. It takes the same `fresh` and `capture_exceptions` arguments as `new_context` and provides a handy way to mark a whole function as being in a new context. For example: + +Python + +PostHog AI + +```python +from posthog import scoped, identify_context +@scoped(fresh=True) +def process_order(user, order_id): + identify_context(user.distinct_id) + posthog.capture("order_processed") # Associated with the user + raise Exception("Order processing failed") # This exception is also captured and associated with the user +``` + +## Group analytics + +Group analytics allows you to associate an event with a group (e.g. teams, organizations, etc.). Read the [Group Analytics](/docs/user-guides/group-analytics.md) guide for more information. + +> **Note:** This is a paid feature and is not available on the open-source or free cloud plan. Learn more on our [pricing page](/pricing.md). + +To capture an event and associate it with a group: + +Python + +PostHog AI + +```python +posthog.capture('some_event', groups={'company': 'company_id_in_your_db'}) +``` + +To update properties on a group: + +Python + +PostHog AI + +```python +posthog.group_identify('company', 'company_id_in_your_db', { + 'name': 'Awesome Inc.', + 'employees': 11 +}) +``` + +The `name` is a special property which is used in the PostHog UI for the name of the group. If you don't specify a `name` property, the group ID will be used instead. + +## Feature flags + +The examples in this section use the synchronous `Posthog` client. For `AsyncPosthog`, use the [awaited feature flag example](#evaluate-feature-flags). The returned snapshot uses the same accessors. + +PostHog's [feature flags](/docs/feature-flags.md) enable you to safely deploy and roll back new features as well as target specific users and groups with them. + +There are two steps to implement feature flags in Python: + +### Step 1: Evaluate flags once + +Call `posthog.evaluate_flags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +Python + +PostHog AI + +```python +flags = posthog.evaluate_flags("distinct_id_of_your_user") +if flags.is_enabled("flag-key"): + # Do something differently for this user + # Optional: fetch the payload + matched_flag_payload = flags.get_flag_payload("flag-key") +``` + +#### Multivariate feature flags + +Python + +PostHog AI + +```python +flags = posthog.evaluate_flags("distinct_id_of_your_user") +enabled_variant = flags.get_flag("flag-key") +if enabled_variant == "variant-key": # replace "variant-key" with the key of your variant + # Do something differently for this user + # Optional: fetch the payload + matched_flag_payload = flags.get_flag_payload("flag-key") +``` + +`flags.get_flag()` returns the variant string for multivariate flags, `True` for enabled boolean flags, `False` for disabled flags, and `None` when the flag wasn't returned by the evaluation. + +> **Note:** `posthog.feature_enabled()`, `posthog.get_feature_flag()`, `posthog.get_feature_flag_payload()`, and `posthog.capture(send_feature_flags=True)` still work during the migration period, but they're deprecated. Prefer `posthog.evaluate_flags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `capture()` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +Python + +PostHog AI + +```python +flags = posthog.evaluate_flags("distinct_id_of_your_user") +if flags.is_enabled("flag-key"): + # Do something differently for this user + pass +posthog.capture( + "event_name", + distinct_id="distinct_id_of_your_user", + flags=flags, +) +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +Python + +PostHog AI + +```python +# Attach only flags accessed with is_enabled() or get_flag() before this call +posthog.capture( + "event_name", + distinct_id="distinct_id_of_your_user", + flags=flags.only_accessed(), +) +# Attach only specific flags +posthog.capture( + "event_name", + distinct_id="distinct_id_of_your_user", + flags=flags.only(["checkout-flow", "new-dashboard"]), +) +``` + +`only_accessed()` is order-dependent. If you call it before accessing any flags with `is_enabled()` or `get_flag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +Python + +PostHog AI + +```python +posthog.capture( + "event_name", + distinct_id="distinct_id_of_the_user", + properties={ + # Replace feature-flag-key with your flag key and "variant-key" with the key of your variant + "$feature/feature-flag-key": "variant-key", + }, +) +``` + +### Evaluating only specific flags + +By default, `posthog.evaluate_flags()` evaluates every flag for the user. If you only need a few flags, pass `flag_keys` to request only those flags: + +Python + +PostHog AI + +```python +flags = posthog.evaluate_flags( + "distinct_id_of_your_user", + flag_keys=["checkout-flow", "new-dashboard"], +) +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](/docs/product-analytics/insights.md) on the flag. With `posthog.evaluate_flags()`, the SDK sends this event when you call `flags.is_enabled()` or `flags.get_flag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.get_flag_payload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `only_accessed()`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](/docs/product-analytics/person-properties.md), [groups](/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +Python + +PostHog AI + +```python +flags = posthog.evaluate_flags( + "distinct_id_of_the_user", + person_properties={"property_name": "value"}, + groups={ + "your_group_type": "your_group_id", + "another_group_type": "your_group_id", + }, + group_properties={ + "your_group_type": {"group_property_name": "value"}, + "another_group_type": {"group_property_name": "value"}, + }, +) +if flags.is_enabled("flag-key"): + # Do something differently for this user +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +### Request timeout + +You can configure the `feature_flags_request_timeout_seconds` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked if PostHog's servers are too slow to respond. By default, this is set to 3 seconds. + +Python + +PostHog AI + +```python +posthog = Posthog( + "", + host="https://us.i.posthog.com", + feature_flags_request_timeout_seconds=3, # Time in seconds. Defaults to 3. +) +``` + +### Local evaluation + +Evaluating feature flags requires making a request to PostHog for each flag. However, you can improve performance by evaluating flags locally. Instead of making a request for each flag, PostHog will periodically request and store feature flag definitions locally, enabling you to evaluate flags without making additional requests. + +It is best practice to use local evaluation flags when possible, since this enables you to resolve flags faster and with fewer API calls. + +For details on how to implement local evaluation, see our [local evaluation guide](/docs/feature-flags/local-evaluation.md). + +#### Distributed environments + +In multi-worker or edge environments, you can implement custom caching for flag definitions using Redis, Cloudflare KV, or other storage backends. This enables sharing definitions across workers and coordinating fetches. See our guide for [local evaluation in distributed environments](/docs/feature-flags/local-evaluation/distributed-environments?tab=Python.md) for details. + +## Experiments (A/B tests) + +Since [experiments](/docs/experiments/start-here.md) use feature flags, the code for running an experiment is very similar to the feature flags code. This example uses the synchronous `Posthog` client: + +Python + +PostHog AI + +```python +flags = posthog.evaluate_flags("user_distinct_id") +variant = flags.get_flag("experiment-feature-flag-key") +if variant == "variant-name": + # Do something +``` + +With `AsyncPosthog`, await the evaluation: `flags = await posthog.evaluate_flags("user_distinct_id")`. The remaining snapshot access is the same. + +It's also possible to [run experiments without using feature flags](/docs/experiments/running-experiments-without-feature-flags.md). + +## AI Observability + +Our Python SDK includes a built-in AI Observability feature. It enables you to capture LLM usage, performance, and more. Check out our [analytics docs](/docs/ai-observability.md) for more details on setting it up. + +## Error tracking + +You can [autocapture exceptions](/docs/error-tracking/installation.md) by setting the `enable_exception_autocapture` argument to `True` when initializing the PostHog client. + +Python + +PostHog AI + +```python +from posthog import Posthog +posthog = Posthog("", enable_exception_autocapture=True, ...) +``` + +You can also manually capture exceptions using the `capture_exception` method: + +Python + +PostHog AI + +```python +posthog.capture_exception(e, distinct_id='user_distinct_id', properties=additional_properties) +``` + +Contexts automatically capture exceptions thrown inside them, unless disable it by passing `capture_exceptions=False` to `new_context()`. + +### Code variables capture + +The Python SDK can automatically capture the state of local variables when an exception occurs. This gives you a debugger-like view of your application state at the time of the error: + +Python + +PostHog AI + +```python +posthog = Posthog( + "", + enable_exception_autocapture=True, + capture_exception_code_variables=True, +) +``` + +You can configure which variables are captured, masked, or ignored. See the [code variables documentation](/docs/error-tracking/code-variables/python.md) for detailed configuration options. + +## GeoIP properties + +Before posthog-python v3.0, we added GeoIP properties to all incoming events by default. We also used these properties for feature flag evaluation, based on the IP address of the request. This isn't ideal since they are created based on your server IP address, rather than the user's, leading to incorrect location resolution. + +As of posthog-python v3.0, the default now is to disregard the server IP, not add the GeoIP properties, and not use the values for feature flag evaluations. + +You can go back to previous behavior by doing setting the `disable_geoip` argument in your initialization to `False`: + +Python + +PostHog AI + +```python +posthog = Posthog('api_key', disable_geoip=False) +``` + +The list of properties that this overrides: + +1. `$geoip_city_name` +2. `$geoip_country_name` +3. `$geoip_country_code` +4. `$geoip_continent_name` +5. `$geoip_continent_code` +6. `$geoip_postal_code` +7. `$geoip_time_zone` + +You can also explicitly chose to enable or disable GeoIP for a single capture request like so: + +Python + +PostHog AI + +```python +posthog.capture('test_event', disable_geoip=True|False) +``` + +## Debug mode + +If you're not seeing the expected events being captured, the feature flags being evaluated, or the surveys being shown, you can enable debug mode to see what's happening. + +You can enable debug mode by setting the `debug` option to `True` in the `PostHog` object. This will enable verbose logs about the inner workings of the SDK. + +Python + +PostHog AI + +```python +posthog.debug = True +``` + +## Disabling requests during tests + +You can disable requests during tests by setting the `disabled` option to `True` in the `PostHog` object. This means no events will be captured or no requests will be sent to PostHog. + +Python + +PostHog AI + +```python +if settings.TEST: + posthog.disabled = True +``` + +## Connection configuration + +The SDK uses HTTP connection pooling internally for better performance. These settings typically need not be changed, but in some environments, such as when running behind NAT gateways, pooled connections may be terminated non-gracefully, causing request failures. + +You can configure connection behavior in several ways. The following settings should be called during initialization, before any API requests are made. + +### Enable TCP keepalive + +TCP keepalive probes help prevent idle connections from being dropped by network infrastructure. This is the recommended approach for most cases where idle connections are terminated. + +Python + +PostHog AI + +```python +import posthog +posthog.enable_keep_alive() +``` + +This enables TCP keepalive with sensible defaults (60 second idle time, 60 second probe interval, 3 probes before timeout). + +### Disable connection pooling + +If you need each request to use a fresh connection, you can disable connection reuse entirely. This will incur additional overhead per request but may be desirable in some circumstances. + +Python + +PostHog AI + +```python +import posthog +posthog.disable_connection_reuse() +``` + +### Custom HTTP socket options + +For advanced use cases, you can configure arbitrary socket options on the underlying HTTP connection. + +Python + +PostHog AI + +```python +import socket +import posthog +posthog.set_socket_options([ + (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), + # Add additional socket options as needed +]) +``` + +Pass `None` to `set_socket_options()` to reset to default behavior. + +## Filtering or modifying events before sending + +Use `before_send` to modify or drop events before they are queued for delivery. Return the modified event dictionary to send it, or `None` to drop it. + +Python + +PostHog AI + +```python +from typing import Any +import posthog +def scrub_pii(event: dict[str, Any]) -> dict[str, Any] | None: + properties = event.get("properties", {}) + if "email" in properties: + email = properties["email"] + properties["email"] = f"***@{email.split('@', 1)[1]}" if "@" in email else "***" + if event.get("event") == "test_event": + return None + return event +client = posthog.Client( + "", + before_send=scrub_pii, +) +``` + +If your callback raises an exception, the SDK logs the error and continues with the original unmodified event. + +## Historical migrations + +You can use the Python or Node SDK to run [historical migrations](/docs/migrate.md) of data into PostHog. To do so, set the `historical_migration` option to `true` when initializing the client. + +PostHog AI + +### Python + +```python +from posthog import Posthog +from datetime import datetime +posthog = Posthog( + '', + host='https://us.i.posthog.com', + debug=True, + historical_migration=True +) +events = [ + { + "event": "batched_event_name", + "properties": { + "distinct_id": "user_id", + "timestamp": datetime.fromisoformat("2024-04-02T12:00:00") + } + }, + { + "event": "batched_event_name", + "properties": { + "distinct_id": "used_id", + "timestamp": datetime.fromisoformat("2024-04-02T12:00:00") + } + } +] +for event in events: + posthog.capture( + distinct_id=event["properties"]["distinct_id"], + event=event["event"], + properties=event["properties"], + timestamp=event["properties"]["timestamp"], + ) +``` + +### Node.js + +```javascript +import { PostHog } from 'posthog-node' +const client = new PostHog( + '', + { + host: 'https://us.i.posthog.com', + historicalMigration: true + } +) +client.debug() +client.capture({ + event: "batched_event_name", + distinctId: "user_id", + properties: {}, + timestamp: "2024-04-03T12:00:00Z" +}) +client.capture({ + event: "batched_event_name", + distinctId: "user_id", + properties: {}, + timestamp: "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. This can lead to lost events if the platform terminates the Python process before the buffer is fully flushed. To avoid this, you can either: + +- Call `posthog.shutdown()` before the process ends. This blocking call attempts to deliver queued events and cleans up the client. +- Enable `sync_mode` when initializing the client so each `posthog.capture()` call attempts delivery before it returns. + +### 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](/docs/libraries/django.md) for how to set up PostHog in Django. Our library includes a [contexts middleware](/docs/libraries/django.md#django-contexts-middleware) that can automatically capture distinct IDs, session IDs, and other properties you can set up with tags. + +## Alternative name + +As our open source project [PostHog](https://github.com/PostHog/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`. + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/.env.example b/apps/basic-integration/fastapi/fastapi3-ai-saas/.env.example index f21035a77..0c9689a33 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/.env.example +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/.env.example @@ -12,3 +12,7 @@ SECRET_KEY=dev-secret-key-change-in-production # Credits DEFAULT_CREDITS=100 + +# PostHog +POSTHOG_PROJECT_TOKEN= +POSTHOG_HOST= diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/config.py b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/config.py index 06e278795..7a022861b 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/config.py +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/config.py @@ -25,6 +25,10 @@ class Settings(BaseSettings): # Credits default_credits: int = 100 + # PostHog + posthog_project_token: str | None = None + posthog_host: str | None = None + class Config: env_file = ".env" env_file_encoding = "utf-8" diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/main.py b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/main.py index e42b75200..8123d458f 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/main.py +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/main.py @@ -1,27 +1,55 @@ """Acme AI - FastAPI SaaS Application.""" +import atexit from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse from fastapi.templating import Jinja2Templates +from posthog import Posthog from app.config import get_settings from app.database import init_db +from app.middleware import PostHogMiddleware from app.routers import auth, generate, pages, api_keys, usage, settings as settings_router settings = get_settings() templates = Jinja2Templates(directory="app/templates") +posthog_client: Posthog | None = None @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan events for startup/shutdown.""" + global posthog_client + + if settings.posthog_project_token and settings.posthog_host: + posthog_client = Posthog( + settings.posthog_project_token, + host=settings.posthog_host, + enable_exception_autocapture=True, + ) + atexit.register(posthog_client.shutdown) + elif settings.debug: + missing_var = ( + "POSTHOG_PROJECT_TOKEN" + if not settings.posthog_project_token + else "POSTHOG_HOST" + ) + raise RuntimeError( + f"{missing_var} variable required by PostHog is missing or un-configured, " + f"this causes events to be silently missed. This error stops appearing " + f"once {missing_var} is configured" + ) + # Initialize database init_db() yield + if posthog_client: + posthog_client.shutdown() + app = FastAPI( title=settings.app_name, @@ -29,6 +57,8 @@ async def lifespan(app: FastAPI): lifespan=lifespan, ) +app.add_middleware(PostHogMiddleware) + # Include routers app.include_router(auth.router) app.include_router(generate.router) diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/middleware.py b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/middleware.py index ecc8126cb..5f0431160 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/middleware.py +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/middleware.py @@ -1,3 +1,64 @@ -"""Middleware module for the application.""" +"""PostHog request-context middleware.""" -# Custom middleware can be added here +from http.cookies import SimpleCookie +from typing import Optional + +from itsdangerous import BadSignature +from posthog import identify_context, new_context, tag + +from app.config import get_settings +from app.database import SessionLocal +from app.dependencies import serializer +from app.models import User + + +class PostHogMiddleware: + """Bind the authenticated user to the PostHog context for each request.""" + + def __init__(self, app): + self.app = app + self.settings = get_settings() + + async def __call__(self, scope, receive, send): + if ( + scope["type"] != "http" + or not self.settings.posthog_project_token + or not self.settings.posthog_host + ): + await self.app(scope, receive, send) + return + + user = self._get_user_from_scope(scope) + with new_context(): + if user: + identify_context(str(user.id)) + tag("email", user.email) + tag("credits", user.credits) + await self.app(scope, receive, send) + + def _get_user_from_scope(self, scope) -> Optional[User]: + """Load the authenticated user from the signed session cookie.""" + headers = dict(scope.get("headers", [])) + cookie_header = headers.get(b"cookie", b"").decode("utf-8") + if not cookie_header: + return None + + cookies = SimpleCookie() + cookies.load(cookie_header) + session_cookie = cookies.get(self.settings.session_cookie_name) + if not session_cookie: + return None + + try: + user_id = serializer.loads(session_cookie.value).get("user_id") + except BadSignature: + return None + + if not user_id: + return None + + db = SessionLocal() + try: + return User.get_by_id(db, user_id) + finally: + db.close() diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/api_keys.py b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/api_keys.py index 988425c8e..8ef4ca709 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/api_keys.py +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/api_keys.py @@ -5,6 +5,7 @@ from fastapi import APIRouter, HTTPException, status from pydantic import BaseModel, Field +from app import main from app.dependencies import DbSession, RequiredUser from app.models import APIKey @@ -73,6 +74,9 @@ async def create_api_key( api_key = APIKey.create(db, user_id=current_user.id, name=request.name) + if main.posthog_client: + main.posthog_client.capture("api_key_created") + return APIKeyCreated( id=api_key.id, name=api_key.name, @@ -104,4 +108,7 @@ async def revoke_api_key( api_key.is_active = False db.commit() + if main.posthog_client: + main.posthog_client.capture("api_key_revoked") + return None diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/auth.py b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/auth.py index 2b564d1d1..3780309b4 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/auth.py +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/auth.py @@ -5,7 +5,9 @@ from fastapi import APIRouter, Form, Request from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.templating import Jinja2Templates +from posthog import identify_context, new_context +from app import main from app.config import get_settings from app.dependencies import CurrentUser, DbSession, RequiredUser, create_session_token from app.models import User @@ -34,9 +36,16 @@ async def login( user = User.authenticate(db, email, password) if user: + if main.posthog_client: + with new_context(): + identify_context(str(user.id)) + main.posthog_client.capture( + "user_logged_in", properties={"auth_method": "password"} + ) + response = RedirectResponse(url="/dashboard", status_code=302) response.set_cookie( - key="session_token", + key=settings.session_cookie_name, value=create_session_token(user.id), httponly=True, samesite="lax", @@ -71,9 +80,16 @@ async def signup( user = User.create(db, email=email, password=password, credits=settings.default_credits) + if main.posthog_client: + with new_context(): + identify_context(str(user.id)) + main.posthog_client.capture( + "user_signed_up", properties={"signup_method": "form"} + ) + response = RedirectResponse(url="/dashboard", status_code=302) response.set_cookie( - key="session_token", + key=settings.session_cookie_name, value=create_session_token(user.id), httponly=True, samesite="lax", @@ -84,6 +100,9 @@ async def signup( @router.get("/logout") async def logout(current_user: RequiredUser): """Logout user.""" + if main.posthog_client: + main.posthog_client.capture("user_logged_out") + response = RedirectResponse(url="/", status_code=302) - response.delete_cookie(key="session_token") + response.delete_cookie(key=settings.session_cookie_name) return response diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/generate.py b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/generate.py index 41a129d17..a7d673a3f 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/generate.py +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/generate.py @@ -5,6 +5,7 @@ from fastapi import APIRouter, HTTPException, status from pydantic import BaseModel, Field +from app import main from app.dependencies import DbSession, RequiredUser from app.models import Generation @@ -76,6 +77,16 @@ async def generate_content( credits_used=credits_needed, ) + if main.posthog_client: + main.posthog_client.capture( + "content_generated", + properties={ + "generation_type": request.generation_type, + "credits_used": credits_needed, + "credits_remaining": current_user.credits, + }, + ) + return GenerateResponse( id=generation.id, content=mock_content, diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/settings.py b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/settings.py index d4baaaa2c..bd9fbd63d 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/settings.py +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/app/routers/settings.py @@ -2,11 +2,12 @@ from typing import Annotated, Optional -from fastapi import APIRouter, Form, Request, HTTPException, status -from fastapi.responses import HTMLResponse, RedirectResponse +from fastapi import APIRouter, Form, Request +from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from pydantic import BaseModel, EmailStr +from app import main from app.dependencies import DbSession, RequiredUser router = APIRouter(prefix="/settings", tags=["settings"]) @@ -28,6 +29,7 @@ class PasswordChange(BaseModel): async def settings_page(request: Request, current_user: RequiredUser, db: DbSession): """User settings page.""" from app.models import APIKey + api_key_count = db.query(APIKey).filter( APIKey.user_id == current_user.id, APIKey.is_active == True @@ -53,7 +55,7 @@ async def update_settings( email: Annotated[str, Form()], ): """Update user settings.""" - from app.models import User, APIKey + from app.models import APIKey, User error = None success = None @@ -66,6 +68,8 @@ async def update_settings( else: current_user.email = email db.commit() + if main.posthog_client: + main.posthog_client.capture("email_updated") success = "Settings updated successfully" else: success = "No changes made" @@ -108,6 +112,8 @@ async def change_password( else: current_user.set_password(new_password) db.commit() + if main.posthog_client: + main.posthog_client.capture("password_changed") success = "Password changed successfully" api_key_count = db.query(APIKey).filter( diff --git a/apps/basic-integration/fastapi/fastapi3-ai-saas/requirements.txt b/apps/basic-integration/fastapi/fastapi3-ai-saas/requirements.txt index 9347f3c06..0d9a64af4 100644 --- a/apps/basic-integration/fastapi/fastapi3-ai-saas/requirements.txt +++ b/apps/basic-integration/fastapi/fastapi3-ai-saas/requirements.txt @@ -8,3 +8,4 @@ jinja2>=3.0.0 python-multipart>=0.0.9 werkzeug>=3.0.0 itsdangerous>=2.0.0 +posthog