首页 > 解决方案 > Python如果对象具有属性

问题描述

我浏览了一些答案,但找不到我正在寻找的确切内容。如果有我可能错过的答案,我很乐意看看它。

我得到一个analytics对象(分析是对象的名称)。它是根据谷歌分析数据构建的。这个想法是我可以从这个对象中提取某个报告get_UserData(使用 user_id)并使用该数据来完成我的程序。

我遇到的问题是我必须遍历 1200 个用户并检查每个用户是否有数据(换句话说,我有一长串可能的用户,但只有一些人是活跃的,只有那些活跃的人在目的)

完成此过程最多可能需要 15 分钟,我想避免不得不拉,get_UserData因为它需要更长的时间。我的计划是绕过get_UserData如果用户没有数据analytics以节省时间

我希望这是有道理的(本质上:我想节省时间,并且是面向对象编程的新手)

我拥有的代码:

def initialise_analytics_reporting():
    """Initializes the analytics reporting service object.

  Returns:
    an authorized analytics reporting service object.
  """

    # Parse command-line arguments.
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        parents=[tools.argparser])
    flags = parser.parse_args([])

    # Set up a Flow object to be used if we need to authenticate.
    flow = client.flow_from_clientsecrets(
        "ga-credentials/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.com.json",
        scope='https://www.googleapis.com/auth/analytics.readonly',
        message=tools.message_if_missing(client_secrets_path))

    # Prepare credentials, and authorize HTTP object with them.
    # If the credentials don't exist or are invalid run through the native client
    # flow. The Storage object will ensure that if successful the good
    # credentials will get written back to a file.
    storage = file.Storage('ga-credentials/analyticsreporting.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, flags)
    http = credentials.authorize(http=httplib2.Http())

    # Build the service object.
    analytics = build('analyticsreporting', 'v4', http=http)
    return analytics


def get_user_Activity(analytics, VIEW_ID, user_id, time):
    """
    :type user_id: str
    """

    # Use the Analytics Service Object to query the Analytics Reporting API V4.
    try:
        if hasattr(analytics.userActivity(), user_id): <<<<----- THIS IS WHAT I HAVE DONE
            x = analytics.userActivity().search(
                body={
                    "viewId": VIEW_ID,
                    "user": {
                        "type": "USER_ID",
                        "userId": user_id
                    },
                    "dateRange": {
                        "startDate": time,
                        "endDate": "yesterday"
                    },
                    "activityTypes": [
                        "PAGEVIEW", "EVENT"
                    ]
                }
            ).execute()
    except:
        pass
    return x

但是在运行这个时,我没有从活跃的用户那里得到任何数据?

请帮忙。

标签: pythongoogle-analytics

解决方案


hasattr函数假设第二个参数是您测试的属性的名称,而不是属性的值。例如,user_id='id'只有在userActivity具有属性 id ( userActivity.id) 时测试才会成功。


推荐阅读