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

يشرح هذا الدليل التوجيهي الخطوات المطلوبة للوصول إلى حساب على "إحصاءات Google"، وإجراء طلبات بحث في واجهات برمجة تطبيقات "إحصاءات Google"، والتعامل مع الردود على واجهة برمجة التطبيقات، وإخراج النتائج. يتم استخدام Core Reporting API v3.0 وManagement API v3.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، وهي الأداة المقترَحة لتثبيت حِزم 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) لتثبيته في نظام بايثون.

الخطوة 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