مرحبًا بواجهة برمجة تطبيقات "إحصاءات Google": بدء استخدام Python السريع للتطبيقات المثبّتة

يوضّح هذا البرنامج التعليمي الخطوات المطلوبة للوصول إلى حساب على "إحصاءات Google"، والاستعلام عن واجهات برمجة تطبيقات "إحصاءات Google"، والتعامل مع ردود واجهة برمجة التطبيقات، ثم عرض النتائج. يتم استخدام الإصدار 3.0 من واجهة برمجة التطبيقات لإعداد التقارير الأساسية والإصدار 3.0 من واجهة برمجة التطبيقات للإدارة وOAuth2.0 في هذا البرنامج التعليمي.

الخطوة 1: تفعيل واجهة برمجة التطبيقات في "إحصاءات Google"

لبدء استخدام Google Analytics API، عليك أولاً استخدام أداة الإعداد التي ترشدك خلال إنشاء مشروع في وحدة تحكّم Google API وتفعيل واجهة برمجة التطبيقات وإنشاء بيانات الاعتماد.

إنشاء معرِّف عميل

من صفحة "بيانات الاعتماد":

  1. انقر على إنشاء بيانات اعتماد واختر رقم تعريف عميل OAuth.
  2. اختَر غير ذلك لـ APP TYPE.
  3. أدخِل اسمًا لبيانات الاعتماد.
  4. انقر على إنشاء.

اختَر بيانات الاعتماد التي أنشأتها للتو وانقر على تنزيل JSON. احفظ الملف الذي تم تنزيله بتنسيق client_secrets.json، حيث ستحتاج إليه لاحقًا في البرنامج التعليمي.

الخطوة 2: تثبيت "مكتبة عملاء Google"

يمكنك إما استخدام مدير حِزم أو تنزيل مكتبة برامج Python يدويًا وتثبيتها:

نقطة

استخدِم 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: تنفيذ عيّنة من الكتاب

بعد تفعيل واجهة برمجة التطبيقات في "إحصاءات Google"، ثبّت مكتبة برامج Google APIs لخدمة Python، واضبط نموذج رمز المصدر الذي أصبح النموذج جاهزًا للتشغيل.

شغِّل النموذج باستخدام:

python HelloAnalytics.py
  1. سيُحمِّل التطبيق صفحة التفويض في أحد المتصفّحات.
  2. إذا لم يسبق لك تسجيل الدخول إلى حسابك على Google، سيُطلب منك تسجيل الدخول. إذا كنت مسجّلاً الدخول إلى حسابات متعددة على Google، سيُطلب منك اختيار حساب واحد لاستخدامه في التفويض.

عند الانتهاء من هذه الخطوات، ينتج عن العيّنة اسم الملف الشخصي الأول في "إحصاءات Google" للمستخدم وعدد الجلسات في آخر سبعة أيام.

باستخدام عنصر خدمة "إحصاءات Google" المفوَّض، يمكنك الآن تشغيل أيٍّ من نماذج الرموز التي تم العثور عليها في مستندات مرجعية واجهة برمجة تطبيقات الإدارة. على سبيل المثال، يمكنك محاولة تغيير الرمز لاستخدام طريقة accountSummary.list.

تحديد المشاكل وحلّها

AttributeError: 'Unit_six_moves_urllib_parse' object لا يتضمن سمة 'urlparse'

يمكن أن يحدث هذا الخطأ في نظام التشغيل Mac OSX حيث يتم تحميل التثبيت التلقائي للوحدة التنظيمية "six" (الاعتمادية على هذه المكتبة) قبل التحميل الذي يتم تثبيته. لحلّ المشكلة، أضِف موقع التثبيت في Pip&#39 إلى متغيّر بيئة النظام PYTHONPATH:

  1. حدِّد موقع تثبيت التطبيقات باستخدام الأمر التالي:

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

  2. أضِف السطر التالي إلى ملف ~/.bashrc، مع استبدال <pip_install_path> بالقيمة المحدّدة أعلاه:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. أعِد تحميل ملف ~/.bashrc في أي نوافذ محطات مفتوحة باستخدام الأمر التالي:

    source ~/.bashrc