发布到Google Analytics(分析),可在Node上运行,无法在Python上运行. [英] Post to Google Analytics, works from Node, fails from Python.... why?

查看:57
本文介绍了发布到Google Analytics(分析),可在Node上运行,无法在Python上运行.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将事件发布到Google Analytics(分析).当我使用下面的NodeJS代码时,它可以正常工作,但是当我使用下面的Python代码时,它会失败.两者都返回HTTP 200,甚至在发布到调试URL时也返回HTTP 200( https://www.google-analytics.com/debug/collect ),两种情况下Google Analytics(分析)都会返回成功详细信息(请参见有效:在以下响应中为true).问题是,从NodeJS发布时,结果显示在GA网站上,而从Python发布时,结果却从不显示.我确实比较了两者的要求,但无法发现差异.

I'm trying to post events to Google Analytics. It works fine when I do it using the NodeJS code below, but fails when I use the Python code below. Both do return a HTTP 200 and even when posting to the debug URL (https://www.google-analytics.com/debug/collect) Google Analytics returns success details in both cases (see valid: true in the response below). The problem is that when posting from NodeJS the result shows up in the GA website, when posting from Python it never shows up. I did compare the requests for both and have not been able to spot a difference.

{
  "hitParsingResult": [ {
    "valid": true,
    "parserMessage": [ ],
    "hit": "/debug/collect?v=1\u0026t=event\u0026tid=XXXXXXX\u0026cid=YYYYYYu0026ec=Slack\u0026ea=SlashCommand\u0026el=whowasat-curl\u0026an=staging.Whereis-Everybody?\u0026aid=staging.whereis-everybody.com"
  } ],
  "parserMessage": [ {
    "messageType": "INFO",
    "description": "Found 1 hit in the request."
  } ]
} 

NodeJS代码为(结果确实显示在Google Analytics(分析)中):

The NodeJS code is (result does show up in Google Analytics):

'use strict';

var request = require('request');
require('request-debug')(request);

function postEventToGA(category, action, label) {

    var options = {
        v: '1',
        t: 'event',
        tid: process.env.GOOGLEANALYTICS_TID,
        cid: process.env.GOOGLEANALYTICS_CID,
        ec: category,
        ea: action,
        el: label,
        an: process.env.STAGE_INFIX + "appname",
        aid: process.env.STAGE_INFIX + "appname"
    };

    console.log("payload: " + JSON.stringify(options))
    request.post({ url: 'https://www.google-analytics.com/collect', form: options }, function (err, response, body) {
        console.log(request)
        if (err) {
            console.log("Failed to post event to Google Analytics, error: " + err);
        } else {
            if (200 != response.statusCode) {
                console.log("Failed to post event to Google Analytics, response code: " + response.statusCode + " error: " + err);
            }
        }
    });

}

postEventToGA("some-category", "some-action", "some-label")

Python代码是(结果未显示在Google Analytics(分析)中:

And the Python code is (result does not show up in Google Analytics):

import json
import logging
import os
import requests

LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)

GOOGLEANALYTICS_TID = os.environ["GOOGLEANALYTICS_TID"]
GOOGLEANALYTICS_CID = os.environ["GOOGLEANALYTICS_CID"]
STAGE_INFIX = os.environ["STAGE_INFIX"]

def post_event(category, action, label):

    payload = {
        "v": "1",
        "t": "event",
        "tid": GOOGLEANALYTICS_TID,
        "cid": GOOGLEANALYTICS_CID,
        "ec": category,
        "ea": action,
        "el": label,
        "an": STAGE_INFIX + "appname,
        "aid": STAGE_INFIX + "appname",
    }

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

    print(response.request.method)
    print(response.request.path_url)
    print(response.request.url)
    print(response.request.body)
    print(response.request.headers)

    print(response.status_code)
    print(response.text)

    if response.status_code != 200:
        LOGGER.warning(
            "Got non 200 response code (%s) while posting to GA.", response.status_code
        )


post_event("some-category", "some-action", "some-label")

您知道为什么NodeJS帖子会显示在Google Analytics(分析)中而Python帖子却不会显示吗?(同时返回HTTP200)

Any idea why the NodeJS post will show up in Google Analytics and the Python post does not? (while both return a HTTP200)

推荐答案

进行了更多测试,发现用户代理HTTP标头是造成此问题的原因.当我在Python代码中将其设置为空字符串时,它可以工作.像这样:

Did some more testing and discovered that the user agent HTTP header was causing the problem. When I set it to an empty string in the Python code it works. Like this:

headers = {"User-Agent": ""}
response = requests.post(
    "https://www.google-analytics.com/collect", payload, headers=headers
)

位于 https://developers.google.com/上的文档analytics/devguides/collection/protocol/v1/reference 确实声明使用了用户代理,但没有明确说明要求是什么.显然不接受"python-requests/2.22.0"(python-requests lib的默认值).

The documentation at https://developers.google.com/analytics/devguides/collection/protocol/v1/reference does state that the user agent is used, but does not clearly state what the requirements are. "python-requests/2.22.0" (default value by python-requests lib) is apparently not accepted.

这篇关于发布到Google Analytics(分析),可在Node上运行,无法在Python上运行.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆