Backends
Flask
Flask analytics with Stickybeak starts by adding its script to your rendered pages; this guide shows you where it belongs and how to track page views, goals and purchase revenue. It is a lighter alternative to Google Analytics for Flask, with live visitors, goals and revenue attribution in one script.
Add the script
Set the site ID
Set
STICKYBEAK_SITE_IDin your production environment only. Copy the ID from Settings in the dashboard.Add a context processor
import os from flask import Flask, session app = Flask(__name__) app.config["STICKYBEAK_SITE_ID"] = os.environ.get("STICKYBEAK_SITE_ID") # unset outside production @app.context_processor def stickybeak(): return { "stickybeak_site": app.config["STICKYBEAK_SITE_ID"], "stickybeak_goal": session.pop("stickybeak_goal", None), }Using an app factory or blueprints? Register it with
app.context_processor(stickybeak)or@bp.app_context_processor.Add it to your base template
Put this before
</head>:<script>window.stickybeak = window.stickybeak || function () { (window.stickybeak.q = window.stickybeak.q || []).push(arguments); };</script> {% if stickybeak_site %} <script defer data-site="{{ stickybeak_site }}" data-domain="example.com" src="https://app.usestickybeak.com/_cfw/s.js" ></script> {% endif %}
Check it's working
Publish first, then follow Verify your install.
Track goals
Give any button or link a data-goal attribute. See Custom goals.
<a href="{{ url_for('pricing') }}" data-goal="view_pricing">Pricing</a>
Fire a goal after a redirect
When a form saves and your view redirects, put the goal in the session.
from flask import redirect, request, session, url_for
@app.post("/signup")
def signup():
user = create_user(request.form)
session["stickybeak_goal"] = {"name": "signup", "props": {"plan": user.plan}}
return redirect(url_for("welcome"))
{% if stickybeak_goal %}
<script>window.stickybeak({{ stickybeak_goal.name|tojson }}, {{ (stickybeak_goal.props or {})|tojson }});</script>
{% endif %}
Track purchases
session["stickybeak_goal"] = {
"name": "purchase",
"props": {"revenue": str(order.total), "currency": "USD", "order_id": str(order.id)},
}
Boosted links and hx-push-url are counted when they push a different path. See Turbo, htmx and friends.
See Revenue.
If it isn't working
- Confirm the environment variable reaches the app server. Sessions require
SECRET_KEY.
See Troubleshooting.