Hello Analytics API: การเริ่มต้นใช้งาน Python อย่างรวดเร็วสำหรับแอปพลิเคชันที่ติดตั้ง

บทแนะนำนี้จะอธิบายขั้นตอนที่จำเป็นในการเข้าถึงบัญชี Google Analytics, ค้นหา Analytics API, จัดการการตอบกลับของ API และแสดงผลลัพธ์ บทแนะนำนี้ใช้ Core Reporting API v3.0, Management API v3.0 และ OAuth2.0

ขั้นตอนที่ 1: เปิดใช้ Analytics API

หากต้องการเริ่มต้นใช้งาน Google Analytics API ก่อนอื่นคุณต้องใช้เครื่องมือการตั้งค่า ซึ่งจะแนะนำขั้นตอนการสร้างโปรเจ็กต์ในคอนโซล Google API เปิดใช้ API และสร้างข้อมูลเข้าสู่ระบบ

สร้างรหัสไคลเอ็นต์

จากหน้าข้อมูลเข้าสู่ระบบ ให้ทำดังนี้

  1. คลิกสร้างข้อมูลเข้าสู่ระบบ แล้วเลือกรหัสไคลเอ็นต์ OAuth
  2. เลือกอื่นๆ สำหรับประเภทแอปพลิเคชัน
  3. ตั้งชื่อข้อมูลเข้าสู่ระบบ
  4. คลิกสร้าง

เลือกข้อมูลเข้าสู่ระบบที่คุณเพิ่งสร้าง แล้วคลิกดาวน์โหลด 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 หลายบัญชี ระบบจะขอให้คุณเลือก 1 บัญชีที่จะใช้ในการให้สิทธิ์

เมื่อทําตามขั้นตอนเหล่านี้เสร็จแล้ว ตัวอย่างจะแสดงชื่อข้อมูลพร็อพเพอร์ตี้ (โปรไฟล์) แรกของ Google Analytics ของผู้ใช้ที่ได้รับอนุญาตและจํานวนเซสชันในช่วง 7 วันที่ผ่านมา

ด้วยออบเจ็กต์บริการ Analytics ที่ได้รับอนุญาต ตอนนี้คุณจะเรียกใช้ตัวอย่างโค้ดที่อยู่ใน เอกสารอ้างอิงของ Management API ได้แล้ว ตัวอย่างเช่น คุณอาจลองเปลี่ยนโค้ดเพื่อใช้เมธอด accountSummaries.list

การแก้ปัญหา

AttributeError: ออบเจ็กต์ "Module_six_moves_urllib_parse" ไม่มีแอตทริบิวต์ "urlparse"

ข้อผิดพลาดนี้อาจเกิดขึ้นใน Mac OSX ที่มีการโหลดการติดตั้งเริ่มต้นของโมดูล "6" (ทรัพยากร Dependency ของไลบรารีนี้) โหลดก่อน 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