简体   繁体   中英

Python if object has attribute

I looked through some answers but couldn't find exactly what I was looking for. If there is an answer that I might have missed, I am happy to take a look at it.

I am getting an analytics object (analytics is the name of the object). It is built from google analytics data. The idea is that I can pull a certain report get_UserData (using user_id) from this object and use that data to finish my program.

The problem I have is that I have to iterate through 1200 users and check if each one has got data (In other words I have a long list of possible users, but only some people were active and only those active people have got data in the object)

It can take up to 15 minutes to finish this process, I want to avoid having to pull the get_UserData because it takes longer. My plan is to bypass the get_UserData if the user doesn't have data in analytics to save time

I hope this makes sense (Essentially: I want to save time, and is new to object-oriented programming)

THE CODE I HAVE:

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

But when running this, I don't get any data from user's who are active??

Please help.

hasattr function suppose the second argument is the name of attribut that you test not the value of attribute. for example if user_id='id' the test will success only if userActivity has an attribut id ( userActivity.id ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM