Chapter 163 · Omnibus Instrument Product Analytics
Subchapter 163.34
references/flask.mdMarkdown3 KBView on GitHub
PostHog makes it easy to get data about traffic and usage of your Flask app. Integrating PostHog enables analytics, custom events capture, feature flags, and more.
This guide walks you through integrating PostHog into your Flask app using the Python SDK.
To start, run pip install posthog to install PostHog’s Python SDK.
Then, initialize PostHog where you’d like to use it. For example, here’s how to capture an event in a simple route:
app.py
PostHog AI
package main
from flask import Flask, render_template, request, redirect, session, url_for
from posthog import Posthog
posthog = Posthog(
'<ph_project_token>',
host='https://us.i.posthog.com'
)
@app.route('/api/dashboard', methods=['POST'])
def api_dashboard():
posthog.capture(
'dashboard_api_called'
distinct_id='distinct_id_of_your_user',
)
return '', 204You can find your project token and instance address in your project settings (opens in a new tab).
Identifying users is required. Backend events need a
distinct_idthat matches the ID your frontend uses when callingposthog.identify(). Without this, backend events are orphaned — they can’t be linked to frontend event captures, session replays (opens in a new tab), LLM traces (opens in a new tab), or error tracking (opens in a new tab).See our guide on identifying users (opens in a new tab) for how to set this up.
Flask has built-in error handlers. This means PostHog’s default exception autocapture won’t work and we need to manually capture errors instead using capture_exception():
Python
PostHog AI
from flask import Flask, jsonify
from posthog import Posthog
posthog = Posthog('<ph_project_token>', host='https://us.i.posthog.com')
@app.errorhandler(Exception)
def handle_exception(e):
# Capture methods, including capture_exception, return the UUID of the captured event,
# which you can use to find specific errors users encountered
event_id = posthog.capture_exception(e)
# You can show the event ID to your user, and ask them to include it in bug reports
response = jsonify({'message': str(e), 'error_id': event_id})
response.status_code = 500
return responseFor any technical questions for how to integrate specific PostHog features into Flask (such as analytics, feature flags, A/B testing, etc.), have a look at our Python SDK docs (opens in a new tab).
Alternatively, the following tutorials can help you get started:
Ask a question
HelpfulCould be better