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. פותחים את הדף חשבון שירות. אם מתבקשים, בוחרים פרויקט.
  2. לוחצים על Create Service Account ומזינים את השם ואת התיאור של חשבון השירות. אפשר להשתמש במספר של חשבון השירות שמוגדר כברירת מחדל, או לבחור מספר אחר וייחודי. בסיום, לוחצים על יצירה.
  3. הקטע הרשאות לחשבון שירות (אופציונלי) לא נדרש. לוחצים על Continue.
  4. במסך Grant users access to this service account גוללים למטה לקטע Create key. לוחצים על Create key.
  5. בחלונית הצדדית שמופיעה, בוחרים את הפורמט של המפתח: מומלץ JSON.
  6. לוחצים על יצירה. זוג המפתחות הציבורי/הפרטי החדש נוצר והורדה למחשב שלך. הוא משמש כעותק היחיד של המפתח הזה. למידע נוסף על אחסון מאובטח, קראו את המאמר ניהול מפתחות של חשבונות שירות.
  7. לוחצים על Close בתיבת הדו-שיח Private key saved to your במחשב, ולאחר מכן לוחצים על Done כדי לחזור לטבלה של חשבונות השירות.

הוספת חשבון שירות לחשבון Google Analytics

כתובת האימייל של חשבון השירות החדש שתיווצר תהיה <projectId>-<uniqueId>@developer.gserviceaccount.com. ניתן להשתמש בכתובת האימייל הזו כדי להוסיף משתמש לחשבון Google Analytics שאליו רוצים לגשת דרך ה-API. במדריך הזה נדרשות רק הרשאות של קריאה וניתוח.

שלב 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 שהורדתם אל אותה ספרייה שבה נמצא הקוד לדוגמה.
  3. החלף את הערכים של key_file_location בערכים המתאימים מ-Developer Console.
"""A simple example of how to access the Google Analytics API."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


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

    Args:
        api_name: The name of the api to connect to.
        api_version: The api version to connect to.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

    Returns:
        A service that is connected to the specified API.
    """

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)

    # Build the service object.
    service = build(api_name, api_version, credentials=credentials)

    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 this 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 within 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):', results.get('profileInfo').get('profileName')
        print 'Total Sessions:', 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'
    key_file_location = '<REPLACE_WITH_JSON_FILE>'

    # Authenticate and construct service.
    service = get_service(
            api_name='analytics',
            api_version='v3',
            scopes=[scope],
            key_file_location=key_file_location)

    profile_id = get_first_profile_id(service)
    print_results(get_results(service, profile_id))


if __name__ == '__main__':
    main()

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

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

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

python HelloAnalytics.py

לאחר ביצוע השלבים האלו, הדגימה תפיק את השם של התצוגה המפורטת הראשונה של המשתמש המורשה ב-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