Google Flask 分析不跟踪页面浏览信息

Google analytics for Flask doesn't track the page view information

我一直在玩 GA (Google-Analytics),但我无法让它跟踪我在其中触发事件的页面视图。

背景

我没有为此使用任何花哨的第 3 方库;按照提供的步骤 here:

,我只 post 一个包含我需要跟踪的东西的 json 对象

我的 Flask 应用程序和他们的 API 之间的连接有效,因为我在浏览我的网站时在我的 GA 仪表板中连接了 1 个用户。

我需要实现的结果是一旦我导航到一条路线,比如 127.0.0.1/projects,我希望该路线显示在我的 Real-Time/Overview/Top Activate Pages.

代码

在我的 utils.py 中,我有一个名为 track_event 的函数,我可以随时导入它

''' Google analytics tracking function. '''
def track_event(event, category, action, label=None, value=0):
    data = {
        'v': '1',  # API Version.
        'tid': current_app.config['GA_TRACKING_ID'],  # Tracking ID / Property ID.
        # Anonymous Client Identifier. Ideally, this should be a UUID that
        # is associated with particular user, device, or browser instance.
        'cid': '555',
        't': event,  # Event hit type.
        'ec': category,  # Event category.
        'ea': action,  # Event action.
        'el': label,  # Event label.
        'ev': value,  # Event value, must be an integer
        'ua': 'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14'
    }

    print(data)

    response = requests.post(
        'https://www.google-analytics.com/collect', data=data)

    print(response.raise_for_status)
    
    # If the request fails, this will raise a RequestException. Depending
    # on your application's needs, this may e a non-error and can be caught by
    # the caller.
    response.raise_for_status()

''' Route of dynamically generated post. '''
@bp.route('/projects/post/<post_id>')
def post(post_id):
    track_event(event=f'/projects/post/{post_id}',category='Projects', action=f'post triggered {post_id}')
    # some more code
    return render_template('post.html', title=f'Project {post_id}', project=project, images=images)

通过查看GA collection parameters,参数t应该是我感兴趣的:

Required for all hit types. The type of hit. Must be one of 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing'.

即便如此,上述仪表板中仍未显示任何内容。任何提示或提示将不胜感激

使用 gtag.js client library 可能更容易。

您可以将其放在全局 HTML 模板的 head 标记中(交换您的 GA_MEASUREMENT_ID)。

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'GA_MEASUREMENT_ID');
</script>

它将自动捕获页面浏览量,除非您通过指定明确关闭它们:

gtag('config', 'GA_MEASUREMENT_ID', { 'send_page_view': false });