Hello Analytics API: מדריך למתחילים של Python לאפליקציות מותקנות

במדריך הזה מפורטים השלבים שצריך לבצע כדי להיכנס לחשבון Google Analytics, לשלוח שאילתות לממשקי ה-API של Analytics, לטפל בתשובות ה-API ולהציג את התוצאות כפלט. במדריך הזה נשתמש בגרסה 3.0 של ממשק ה-API הראשי לדיווח, ב-Management API v3.0 וב-OAuth2.0.

שלב 1: מפעילים את Analytics API

על מנת להתחיל להשתמש ב-Google Analytics API, תחילה צריך להשתמש בכלי ההגדרה, שמדריך אתכם ביצירת פרויקט במסוף Google API, הפעלת ה-API ויצירת פרטי כניסה.

יצירת מזהה לקוח

מהדף 'פרטי כניסה':

  1. לוחצים על Create Credentials (יצירת פרטי כניסה) ובוחרים באפשרות OAuth client ID (מזהה לקוח OAuth).
  2. בשדה סוג האפליקציה, בוחרים באפשרות אחר.
  3. נותנים שם לפרטי הכניסה.
  4. לוחצים על יצירה.

בוחרים את פרטי הכניסה שיצרתם ולוחצים על Download JSON. שומרים את הקובץ שהורדתם בשם client_secrets.json. תצטרכו אותו מאוחר יותר במדריך.

שלב 2: התקנת ספריית הלקוח של Google

אפשר להשתמש במנהל חבילות או להוריד ולהתקין את ספריית הלקוח של Python באופן ידני:

pip

משתמשים ב-pip, הכלי המומלץ להתקנת חבילות Python:

sudo pip install --upgrade google-api-python-client

כלי הגדרה

משתמשים בכלי easy_install שכלול בחבילה של setuptools:

sudo easy_install --upgrade google-api-python-client

התקנה ידנית

הורידו את ספריית הלקוח העדכנית עבור python, פתחו את הקוד והפעילו:

sudo python setup.py install

יכול להיות שתצטרכו להפעיל את הפקודה עם ההרשאות של משתמש-העל (sudo) כדי להתקין ב-Python למערכת.

שלב 3: מגדירים את הדוגמה

עליך ליצור קובץ יחיד בשם HelloAnalytics.py, שיכיל את הקוד לדוגמה הנתון.

  1. צריך להעתיק או להוריד את קוד המקור הבא אל HelloAnalytics.py.
  2. מעבירים את הקובץ client_secrets.json שהורדתם אל אותה ספרייה שבה נמצא הקוד לדוגמה.
"""A simple example of how to access the Google Analytics API."""

import argparse

from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools


def get_service(api_name, api_version, scope, client_secrets_path):
  """Get a service that communicates to a Google API.

  Args:
    api_name: string The name of the api to connect to.
    api_version: string The api version to connect to.
    scope: A list of strings representing the auth scopes to authorize for the
      connection.
    client_secrets_path: string A path to a valid client secrets file.

  Returns:
    A service that is connected to the specified API.
  """
  # 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(
      client_secrets_path, scope=scope,
      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(api_name + '.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.
  service = build(api_name, api_version, http=http)

  return service


def get_first_profile_id(service):
  # Use the Analytics service object to get the first profile id.

  # Get a list of all Google Analytics accounts for the authorized user.
  accounts = service.management().accounts().list().execute()

  if accounts.get('items'):
    # Get the first Google Analytics account.
    account = accounts.get('items')[0].get('id')

    # Get a list of all the properties for the first account.
    properties = service.management().webproperties().list(
        accountId=account).execute()

    if properties.get('items'):
      # Get the first property id.
      property = properties.get('items')[0].get('id')

      # Get a list of all views (profiles) for the first property.
      profiles = service.management().profiles().list(
          accountId=account,
          webPropertyId=property).execute()

      if profiles.get('items'):
        # return the first view (profile) id.
        return profiles.get('items')[0].get('id')

  return None


def get_results(service, profile_id):
  # Use the Analytics Service Object to query the Core Reporting API
  # for the number of sessions in the past seven days.
  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='7daysAgo',
      end_date='today',
      metrics='ga:sessions').execute()


def print_results(results):
  # Print data nicely for the user.
  if results:
    print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
    print 'Total Sessions: %s' % results.get('rows')[0][0]

  else:
    print 'No results found'


def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.readonly']

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, 'client_secrets.json')
  profile = get_first_profile_id(service)
  print_results(get_results(service, profile))


if __name__ == '__main__':
  main()

שלב 4: מריצים את הדוגמה

אחרי שמפעילים את Analytics API, מתקינים את ספריית הלקוח של Google APIs עבור Python ומגדירים את קוד המקור לדוגמה. הדוגמה מוכנה להרצה.

מריצים את הדוגמה באמצעות:

python HelloAnalytics.py
  1. האפליקציה תטען את דף ההרשאה בדפדפן.
  2. אם עדיין לא התחברת לחשבון Google, תוצג לך בקשה להתחבר. אם אתם מחוברים למספר חשבונות Google, תתבקשו לבחור חשבון אחד שישמש לצורך ההרשאה.

לאחר ביצוע השלבים האלו, הדגימה תפיק את השם של התצוגה המפורטת הראשונה של המשתמש המורשה ב-Google Analytics ואת מספר הסשנים בשבעת הימים האחרונים.

בעזרת אובייקט השירות המורשה של Analytics, תוכלו עכשיו להריץ כל דוגמאות קוד שמופיעות ב מסמכי העזר של Management API. לדוגמה, תוכלו לנסות לשנות את הקוד כדי להשתמש בשיטה accountSummaries.list.

פתרון בעיות

AttributeError: לאובייקט 'Module_six_moves_urllib_parse' אין מאפיין 'urlparse'

השגיאה הזו עלולה להתרחש ב-Mac OSX, כאשר התקנת ברירת המחדל של המודול "6" (תלויה בספרייה הזו) נטענת לפני המודול שהותקן ב-PIP. כדי לפתור את הבעיה, צריך להוסיף את מיקום ההתקנה של PIP למשתנה סביבת המערכת PYTHONPATH:

  1. אפשר לקבוע את מיקום ההתקנה של PIP באמצעות הפקודה הבאה:

    pip show six | grep "Location:" | cut -d " " -f2
    

  2. מוסיפים את השורה הבאה לקובץ ~/.bashrc ומחליפים את <pip_install_path> בערך שנקבע למעלה:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. טוענים מחדש את קובץ ~/.bashrc בכל חלון טרמינל פתוח באמצעות הפקודה הבאה:

    source ~/.bashrc