Analytics Reporting API v4 您好:已安裝應用程式的 Python 快速入門導覽課程

本教學課程將逐步介紹存取 Analytics (分析) Reporting API v4 的必要步驟。

1. 啟用 API

如要開始使用 Analytics Reporting API v4,請先使用設定工具。這項工具會引導您在 Google API 控制台中建立專案、啟用 API,並建立憑證。

注意:您必須在同意畫面中設定產品名稱,才能建立網路用戶端 ID 或已安裝的應用程式用戶端。如果尚未設定,系統會提示你設定同意畫面

建立憑證

  • 開啟「Credentials」(憑證) 頁面
  • 按一下「建立憑證」,然後選取「OAuth 用戶端 ID」
  • 在「應用程式類型」部分,選取「其他」。
  • 將用戶端 ID 命名為 quickstart,然後點選「Create」(建立)

在「憑證」頁面中,按一下新建立的用戶端 ID,然後點選「下載 JSON」,並將其儲存為 client_secrets.json;後續步驟將會用到。

2. 安裝用戶端程式庫

如要安裝 Python 套件,建議使用 pipvenv: sudo -s apt-get install python3-venv python3 -m venv analytics-quickstart source analytics-quickstart/bin/activate pip install --upgrade google-api-python-client pip install --upgrade oauth2client

3. 設定範例

您需要建立名為 HelloAnalytics.py 的單一檔案,其中含有指定的程式碼範例。

  1. 將下列原始碼複製或下載HelloAnalytics.py
  2. 將先前下載的 client_secrets.json 移至與程式碼範例相同的目錄。
  3. 取代 VIEW_ID 的值。您可以使用 Account Explorer 找出資料檢視 ID。
"""Hello Analytics Reporting API V4."""

import argparse

from apiclient.discovery import build
import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_analyticsreporting():
  """Initializes the analyticsreporting service object.

  Returns:
    analytics an authorized analyticsreporting service object.
  """
  # 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=SCOPES,
      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('analyticsreporting.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.
  analytics = build('analyticsreporting', 'v4', http=http)

  return analytics

def get_report(analytics):
  # Use the Analytics Service Object to query the Analytics Reporting API V4.
  return analytics.reports().batchGet(
      body={
        'reportRequests': [
        {
          'viewId': VIEW_ID,
          'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
          'metrics': [{'expression': 'ga:sessions'}]
        }]
      }
  ).execute()


def print_response(response):
  """Parses and prints the Analytics Reporting API V4 response"""

  for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
    rows = report.get('data', {}).get('rows', [])

    for row in rows:
      dimensions = row.get('dimensions', [])
      dateRangeValues = row.get('metrics', [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print header + ': ' + dimension

      for i, values in enumerate(dateRangeValues):
        print 'Date range (' + str(i) + ')'
        for metricHeader, value in zip(metricHeaders, values.get('values')):
          print metricHeader.get('name') + ': ' + value


def main():

  analytics = initialize_analyticsreporting()
  response = get_report(analytics)
  print_response(response)

if __name__ == '__main__':
  main()

4. 執行範例

使用下列指令執行範例:

python HelloAnalytics.py
  • 應用程式會在瀏覽器中載入授權頁面。
  • 如果您尚未登入 Google 帳戶,系統會提示您登入。如果您登入多個 Google 帳戶,系統會要求您選取其中一個帳戶進行授權。

完成這些步驟後,範例會輸出最近七天內的指定資料檢視數量。

疑難排解

AttributeError:「Module_six_moves_urllib_parse」物件沒有「urlparse」屬性

在 Mac OSX 中,可能會發生這個錯誤,因為系統先載入「six」模組 (這個程式庫的依附元件) 的預設安裝作業,再載入 pip 安裝的模組。如要修正這個問題,請將 pip 的安裝位置新增到 PYTHONPATH 系統環境變數:

  • 請使用下列指令判斷 pip 的安裝位置:

    管線展示 6 | grep "Location:" | 剪下 -d " " -f2

  • ~/.bashrc 檔案中新增下列程式碼,將 &lt;pip_install_path&gt; 替換為上述決定的值:

    匯出 PYTHONPATH=$PYTHONPATH:<pip_install_path>

  • 使用下列指令,在開啟的終端機視窗中重新載入 ~/.bashrc 檔案:

    來源 ~/.bashrc