使用 userActivity.search 使用 python 从 google 分析中获取用户数据

Fetch user data from google analytics with python using userActivity.search

我正在尝试使用以下 google python api:

从 google 分析中获取用户数据

https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py

在所示示例中,函数 'get_report' 如下所示:

def get_report(analytics):
  """Queries the Analytics Reporting API V4.

  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}],
          'dimensions': [{'name': 'ga:country'}]
        }]
      }
  ).execute()

此语法运行良好,但为了获取用户数据,我认为我必须遵守以下手册:

https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/userActivity/search

为了让它更清楚,我想 运行 来自这里的例子:

https://developers.google.com/analytics/devguides/reporting/core/v4/user-reporting

示例如下所示:

{
    "viewId": "9999999",
    "user": {
        "type": "CLIENT_ID",
        "userId": "1034600000.76425000000"
    },
    "dateRange": {
        "startDate": "2018-01-01",
        "endDate": "2018-12-31",
    }
}

但是这个例子并没有说明如何从上面定义函数"get_report"。 根据我的理解,'get_reports' 中使用的参数 'analysis' 有一个方法或 class 称为 'userActivity' 它有。但是根据上面的第二个 link 它也应该有一个叫做 'search' 的方法,它没有!那么我如何get/access方法'search'呢? class 'userActivity'初始化的时候需要初始化吗?

目前我的语法是这样的:

def get_report(analytics):
  """Queries the Analytics Reporting API V4.

  Args:
    analytics: An authorized Analytics Reporting API V4 service object.
  Returns:
    The Analytics Reporting API V4 response.
  """
  return analytics.userActivity().search(
      {
    "viewId": VIEW_ID,
    "user": {
        "type": "CLIENT_ID",
        "userId": "310383817.1547668323"
    },
    "dateRange": {
        "startDate": "2019-01-30",
        "endDate": "2019-02-01",
    }
}
  ).execute()

但是这种语法有效!错误消息说:

method() 采用 1 个位置参数,但给出了 2 个

感谢您的帮助!

我刚找到答案...
您只需将搜索方法的参数放入一个名为 body 的变量中。它应该是这样的:

def get_report(analytics):
    """Queries the Analytics Reporting API V4.

    Args:
        analytics: An authorized Analytics Reporting API V4 service object.
    Returns:
        The Analytics Reporting API V4 response.
    """
    return analytics.userActivity().search(
        body = {
            "viewId": VIEW_ID,
            "user": {
                "type": "CLIENT_ID",
                "userId": "310383817.1547668323"
            },
            "dateRange": {
                "startDate": "2019-01-30",
                "endDate": "2019-02-01",
            }
        }
    ).execute()