Hello Analytics API: 설치된 애플리케이션을 위한 Python 빠른 시작

이 튜토리얼에서는 Google 애널리틱스 계정에 액세스하고, 애널리틱스 API를 쿼리하고, API 응답을 처리하고, 결과를 출력하는 데 필요한 단계를 안내합니다. 이 가이드에서는 Core Reporting API v3.0, Management API v3.0, OAuth2.0을 사용합니다.

1단계: Analytics API 사용 설정

Google 애널리틱스 API를 사용하려면 먼저 설정 도구를 사용해야 합니다. 이 도구는 Google API 콘솔에서 프로젝트를 만들고, API를 사용 설정하고, 사용자 인증 정보를 만드는 방법을 안내합니다.

클라이언트 ID 만들기

사용자 인증 정보 페이지에서 다음을 수행합니다.

  1. 사용자 인증 정보 만들기를 클릭하고 OAuth 클라이언트 ID를 선택합니다.
  2. 애플리케이션 유형으로 기타를 선택합니다.
  3. 사용자 인증 정보의 이름을 지정합니다.
  4. 만들기를 클릭합니다.

방금 만든 사용자 인증 정보를 선택하고 JSON 다운로드를 클릭합니다. 다운로드한 파일을 client_secrets.json로 저장합니다. 이 파일은 가이드의 후반부에 필요합니다.

2단계: Google 클라이언트 라이브러리 설치

패키지 관리자를 사용하거나 Python 클라이언트 라이브러리를 수동으로 다운로드하여 설치할 수 있습니다.

pip

Python 패키지 설치에 권장되는 도구인 pip를 사용합니다.

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

설정 도구

setuptools 패키지에 포함된 easy_install 도구를 사용하세요.

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

수동 설치

최신 Python용 클라이언트 라이브러리를 다운로드하고 코드의 압축을 풀고 다음을 실행합니다.

sudo python setup.py install

시스템 Python에 설치하려면 수퍼유저 (sudo) 권한으로 명령어를 호출해야 할 수도 있습니다.

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를 사용 설정하고 Python용 Google API 클라이언트 라이브러리를 설치하고 샘플을 실행할 수 있는 샘플 소스 코드를 설정합니다.

다음을 사용하여 샘플을 실행합니다.

python HelloAnalytics.py
  1. 애플리케이션이 브라우저에 인증 페이지를 로드합니다.
  2. 아직 Google 계정에 로그인하지 않았다면 로그인하라는 메시지가 표시됩니다. 여러 Google 계정에 로그인되어 있는 경우 승인에 사용할 계정 하나를 선택하라는 메시지가 표시됩니다.

이 단계를 완료하면 샘플에서 승인된 사용자의 첫 번째 Google 애널리틱스 보기 (프로필) 이름과 지난 7일간의 세션수를 출력합니다.

이제 승인된 애널리틱스 서비스 객체를 사용하여 Management API 참조 문서에 있는 코드 샘플을 실행할 수 있습니다. 예를 들어 accountSummaries.list 메서드를 사용하도록 코드를 변경할 수 있습니다.

문제 해결

AttributeError: 'Module_six_moves_urllib_parse' 객체에 'urlparse' 속성이 없음

이 오류는 'six' 모듈 (이 라이브러리의 종속 항목)의 기본 설치가 pip가 설치된 모듈보다 먼저 로드되는 Mac OSX에서 발생할 수 있습니다. 이 문제를 해결하려면 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