首页 > 解决方案 > Flask 的 Google 分析不跟踪页面查看信息

问题描述

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

背景

我没有为此使用任何花哨的 3rd 方库;按照此处提供的步骤,我只发布了一个包含我需要跟踪的内容的 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 集合参数,该参数t应该是我感兴趣的参数:

所有命中类型都需要。命中类型。必须是“pageview”、“screenview”、“event”、“transaction”、“item”、“social”、“exception”、“timing”之一。

即使这样,上述仪表板中也没有显示任何内容。任何提示或提示将不胜感激

标签: pythonflaskgoogle-analytics

解决方案


使用gtag.js 客户端库可能更容易。

你可以把它放在你的全局 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 });

推荐阅读