Hello Analytics API: التشغيل السريع للغة Python لحسابات الخدمة

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

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

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

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

  1. افتح صفحة حسابات الخدمة. اختَر مشروعًا إذا طُلب منك ذلك.
  2. انقر على إنشاء حساب للخدمة ثم أدخِل اسمًا ووصفًا لحساب الخدمة. يمكنك استخدام معرّف حساب الخدمة التلقائي أو اختيار معرّف فريد مختلف. وعند الانتهاء من ذلك، انقر على إنشاء.
  3. قسم أذونات حساب الخدمة (اختيارية) التالي غير مطلوب. انقر على متابعة.
  4. انتقِل إلى القسم إنشاء مفتاح في أسفل شاشة منح المستخدمين صلاحية الوصول إلى حساب الخدمة هذا. انقر على إنشاء مفتاح.
  5. في اللوحة الجانبية التي تظهر، اختَر التنسيق الخاص بالمفتاح: وننصح باستخدام JSON.
  6. انقر على إنشاء. يتم إنشاء زوج المفتاح العام/الخاص وتنزيله على جهازك، وهو النسخة الوحيدة من هذا المفتاح. للحصول على معلومات عن طريقة التخزين الآمن للمفتاح، يُرجى مراجعةإدارة مفاتيح حساب الخدمة.
  7. انقر على إغلاق في مربّع الحوار تم حفظ المفتاح الخاص على الكمبيوتر، ثم انقر على تم للرجوع إلى جدول حسابات الخدمة.

إضافة حساب الخدمة إلى حساب "إحصاءات Google"

سيكون لحساب الخدمة الذي تم إنشاؤه حديثًا عنوان بريد إلكتروني <projectId>-<uniqueId>@developer.gserviceaccount.com. استخدِم عنوان البريد الإلكتروني هذا لإضافة مستخدم إلى حساب "إحصاءات Google" الذي تريد الوصول إليه عبر واجهة برمجة التطبيقات. يتطلب هذا البرنامج التعليمي أذونات القراءة والتحليل فقط.

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

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

pip

استخدِم pip، وهي الأداة التي يُنصح بها لتثبيت حِزم بايثون:

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) للتثبيت على نظام بايثون.

الخطوة 3: إعداد النموذج

يجب إنشاء ملف واحد باسم HelloAnalytics.py يتضمّن الرمز النموذجي المتوفر.

  1. انسخ أو نزِّل رمز المصدر التالي إلى HelloAnalytics.py.
  2. انقل ملف client_secrets.json الذي سبق تنزيله إلى الدليل نفسه الذي يتضمّن الرمز النموذجي.
  3. استبدِل قيم key_file_location بالقيم المناسبة من Play 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: تشغيل العيّنة

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

تنفيذ العيّنة باستخدام:

python HelloAnalytics.py

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

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

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

AttributeError: الكائن 'Module_six_moves_urllib_parse' لا يحتوي على سمة "urlparse"

يمكن أن يحدث هذا الخطأ في نظام التشغيل Mac OSX حيث يتم تحميل التثبيت الافتراضي للوحدة "ستة" (تبعية لهذه المكتبة) قبل الوحدة المثبتة على 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