OnyxMetric
Integration Guides

Flask

Add OnyxMetric analytics to your Flask app

Flask renders Jinja templates, usually through a shared base layout, so the tag belongs in that layout's <head>. Flask exposes app.config to every template as config, which makes it a natural home for the site ID.

Copy your tracking snippet

In OnyxMetric, open your site's Site Settings and copy the tracking script. It looks like this:

<script src="https://app.onyxmetric.com/api/script.js?siteId=YOUR_SITE_ID" async></script>

YOUR_SITE_ID is the numeric ID of your site.

Add the snippet to Flask

Configure the site ID

Variables prefixed with FLASK_ are loaded into app.config by from_prefixed_env():

.env
FLASK_ONYXMETRIC_SITE_ID=YOUR_SITE_ID
app.py
from flask import Flask, render_template

app = Flask(__name__)
app.config.from_prefixed_env()


@app.route("/")
def index():
    return render_template("index.html")

If your settings live in a Python file or class, add ONYXMETRIC_SITE_ID there and use app.config.from_object().

Edit the base layout

templates/base.html
<head>
    <meta charset="utf-8">
    <title>{% block title %}My App{% endblock %}</title>

    {% if config.ONYXMETRIC_SITE_ID %}
    <script src="https://app.onyxmetric.com/api/script.js?siteId={{ config.ONYXMETRIC_SITE_ID }}" async></script>
    {% endif %}
</head>

config is part of Flask's standard template context, so no context processor is needed. When the ID is unset the tag is skipped, which keeps development untracked. Templates that do not extend the base need the tag too.

Check that it works

Load your live site and click through a few pages. Pageviews show up in the OnyxMetric dashboard within seconds.

If nothing arrives:

  • View the page source and search for script.js?siteId= to confirm the tag is present.
  • In the browser's Network tab, check that script.js returns 200 and that requests go to /api/track.
  • Turn off ad blockers, or proxy the script through your own domain.
  • Read script troubleshooting for other causes.

Troubleshooting

  • Tag missing: configuration is read when the app is created. Restart after changing FLASK_ONYXMETRIC_SITE_ID and check app.config["ONYXMETRIC_SITE_ID"] in flask shell.
  • Imported macros: config is in the render context, not in imported templates, so a macro that prints the tag must be imported with context.
  • Flask-Talisman or other CSP: allow app.onyxmetric.com in script-src and connect-src, or proxy the script.

Next steps

On this page