Xin chào Analytics API: Bắt đầu nhanh Python cho các ứng dụng đã cài đặt

Tài liệu hướng dẫn này trình bày các bước cần thiết để truy cập vào tài khoản Google Analytics, truy vấn API Analytics, xử lý các phản hồi của API và xuất kết quả. API Báo cáo chính phiên bản 3.0, API Quản lý phiên bản 3.0API OAuth2.0 được sử dụng trong hướng dẫn này.

Bước 1: Bật Analytics API

Để bắt đầu sử dụng API Google Analytics, trước tiên bạn cần sử dụng công cụ thiết lập. Công cụ này sẽ hướng dẫn bạn cách tạo dự án trong Google API Console, bật API và tạo thông tin đăng nhập.

Tạo mã ứng dụng khách

Trên trang Thông tin xác thực:

  1. Nhấp vào Tạo thông tin xác thực rồi chọn Mã ứng dụng khách OAuth.
  2. Chọn Other cho APPLICATION TYPE (Loại ứng dụng).
  3. Đặt tên cho thông tin xác thực.
  4. Nhấp vào Tạo.

Chọn thông tin đăng nhập bạn vừa tạo rồi nhấp vào Tải JSON xuống. Lưu tệp đã tải xuống dưới dạng client_secrets.json; sau này bạn sẽ cần đến tệp này trong hướng dẫn.

Bước 2: Cài đặt Thư viện ứng dụng của Google

Bạn có thể sử dụng trình quản lý gói hoặc tải xuống và cài đặt thư viện ứng dụng Python theo cách thủ công:

pip

Hãy dùng pip, công cụ được đề xuất để cài đặt các gói Python:

sudo pip install --upgrade google-api-python-client

Công cụ thiết lập

Sử dụng công cụ easy_install có trong gói setuptools:

sudo easy_install --upgrade google-api-python-client

Cài đặt theo cách thủ công

Tải thư viện ứng dụng cho python mới nhất xuống, giải nén mã và chạy:

sudo python setup.py install

Bạn có thể phải gọi lệnh này bằng các đặc quyền của siêu người dùng (sudo) để cài đặt vào hệ thống Python.

Bước 3: Thiết lập mẫu

Bạn cần tạo một tệp có tên HelloAnalytics.py chứa mã mẫu đã cho.

  1. Sao chép hoặc tải mã nguồn sau xuống HelloAnalytics.py.
  2. Di chuyển client_secrets.json đã tải xuống trước đó vào cùng thư mục với mã mẫu.
"""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()

Bước 4: Chạy mẫu

Sau khi bạn bật API Analytics, hãy cài đặt thư viện ứng dụng API của Google cho Python, và thiết lập mã nguồn mẫu để mẫu sẵn sàng chạy.

Chạy mẫu bằng cách sử dụng:

python HelloAnalytics.py
  1. Ứng dụng sẽ tải trang cấp phép trong trình duyệt.
  2. Nếu chưa đăng nhập vào Tài khoản Google của mình, bạn sẽ được nhắc đăng nhập. Nếu đăng nhập vào nhiều Tài khoản Google, bạn sẽ được yêu cầu chọn một tài khoản để uỷ quyền.

Khi bạn hoàn tất những bước này, mẫu sẽ hiển thị tên của chế độ xem (hồ sơ) Google Analytics đầu tiên của người dùng được uỷ quyền và số phiên trong 7 ngày qua.

Với đối tượng dịch vụ Analytics được uỷ quyền, giờ đây, bạn có thể chạy mọi mã mẫu có trong tài liệu tham khảo về API Quản lý. Ví dụ: bạn có thể thử thay đổi mã để sử dụng phương thức accountSummaries.list.

Khắc phục sự cố

Lỗi thuộc tính: Đối tượng "Module_six_moves_urllib_parse" không có thuộc tính "urlparse"

Lỗi này có thể xảy ra trong Mac OSX, trong đó cài đặt mặc định của mô-đun "6" (phần phụ thuộc của thư viện này) được tải trước mô-đun mà pip cài đặt. Để khắc phục vấn đề này, hãy thêm vị trí cài đặt của pip vào biến môi trường hệ thống PYTHONPATH:

  1. Xác định vị trí cài đặt của pip bằng lệnh sau:

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

  2. Thêm dòng sau vào tệp ~/.bashrc, thay thế <pip_install_path> bằng giá trị được xác định ở trên:

    export PYTHONPATH=$PYTHONPATH:<pip_install_path>
    
  3. Tải lại tệp ~/.bashrc trong mọi cửa sổ dòng lệnh đang mở bằng lệnh sau:

    source ~/.bashrc