Hello Analytics Reporting API v4; 설치된 애플리케이션용 Python 빠른 시작

이 튜토리얼에서는 Analytics Reporting API v4에 액세스하는 데 필요한 단계를 안내합니다.

1. API 사용 설정

애널리틱스 Reporting API v4를 사용하려면 먼저 설정 도구를 사용하여 Google API 콘솔에서 프로젝트를 만들고 API를 사용 설정하며 사용자 인증 정보를 만드는 과정을 진행합니다.

참고: 웹 클라이언트 ID 또는 설치된 애플리케이션 클라이언트를 만들려면 동의 화면에서 제품 이름을 설정해야 합니다. 아직 구성하지 않았다면 동의 화면 구성하라는 메시지가 표시됩니다.

사용자 인증 정보 만들기

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

사용자 인증 정보 페이지에서 새로 만든 클라이언트 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의 값을 바꿉니다. 계정 탐색기를 사용하여 보기 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 계정에 로그인되어 있는 경우 승인에 사용할 계정을 하나 선택하라는 메시지가 표시됩니다.

이 단계를 완료하면 샘플에서는 지정된 뷰의 지난 7일 동안의 세션 수를 출력합니다.

문제 해결

AttributeError: 'Module_six_moves_urllib_parse' 객체에 속성 #&93;urlparse'이 없습니다.

이 오류는 pip가 설치된 버전 전에 기본 모듈 (이 라이브러리의 종속 항목)이 로드되는 Mac OSX에서 발생할 수 있습니다. 문제를 해결하려면 pip의 설치 위치를 PYTHONPATH 시스템 환경 변수에 추가합니다.

  • 다음 명령어를 사용하여 pip의 설치 위치를 확인합니다.

    pip show 6 | grep "Location:" | Cut -d " -f2

  • ~/.bashrc 파일에 다음 줄을 추가하고 &lt;pip_install_path&gt;를 위에서 결정한 값으로 바꿉니다.

    Export PYTHONPATH=$PYTHONPATH:<pip_install_path>

  • 다음 명령어를 사용하여 열려 있는 터미널 창에서 ~/.bashrc 파일을 다시 로드합니다.

    소스 ~/.bashrc