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. 서비스 계정 페이지를 엽니다. 메시지가 표시되면 프로젝트를 선택합니다.
  2. 서비스 계정 만들기를 클릭한 다음 서비스 계정의 이름과 설명을 입력합니다. 기본 서비스 계정 ID를 사용하거나 다른 고유한 ID를 선택할 수도 있습니다. 완료하면 만들기를 클릭합니다.
  3. 이어지는 서비스 계정 권한(선택사항) 섹션은 선택하지 않아도 됩니다. 계속을 클릭합니다.
  4. 사용자에게 이 서비스 계정에 대한 액세스 권한 부여 화면에서 키 만들기 섹션이 나올 때까지 아래로 스크롤합니다. 키 만들기를 클릭합니다.
  5. 표시되는 측면 패널에서 키 형식을 선택합니다. JSON이 권장됩니다.
  6. 만들기를 클릭합니다. 새로운 공개 키/비공개 키 쌍이 생성되어 기기에 다운로드됩니다. 생성된 파일은 이 키의 유일한 사본으로 사용됩니다. 키를 안전하게 보관하는 방법을 자세히 알아보려면 서비스 계정 키 관리를 참조하세요.
  7. 개인 키가 컴퓨터에 저장되었습니다 대화상자에서 닫기를 클릭한 다음 완료를 클릭하여 서비스 계정 표로 돌아갑니다.

Google 애널리틱스 계정에 서비스 계정 추가

새로 만든 서비스 계정에는 <projectId>-<uniqueId>@developer.gserviceaccount.com이라는 이메일 주소가 포함됩니다. 이 이메일 주소를 사용하여 API를 통해 액세스할 Google 애널리틱스 계정에 사용자를 추가합니다. 이 가이드에서는 읽기 및 분석 권한만 있으면 됩니다.

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를 샘플 코드와 동일한 디렉터리로 이동합니다.
  3. key_file_location의 값을 Play Console의 적절한 값으로 바꿉니다.
"""A simple example of how to access the Google Analytics API."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


def get_service(api_name, api_version, scopes, key_file_location):
    """Get a service that communicates to a Google API.

    Args:
        api_name: The name of the api to connect to.
        api_version: The api version to connect to.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

    Returns:
        A service that is connected to the specified API.
    """

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)

    # Build the service object.
    service = build(api_name, api_version, credentials=credentials)

    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 this 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 within 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):', results.get('profileInfo').get('profileName')
        print 'Total Sessions:', 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'
    key_file_location = '<REPLACE_WITH_JSON_FILE>'

    # Authenticate and construct service.
    service = get_service(
            api_name='analytics',
            api_version='v3',
            scopes=[scope],
            key_file_location=key_file_location)

    profile_id = get_first_profile_id(service)
    print_results(get_results(service, profile_id))


if __name__ == '__main__':
    main()

4단계: 샘플 실행

Analytics API를 사용 설정한 후에는 Python용 Google API 클라이언트 라이브러리를 설치하고 샘플을 실행할 수 있는 샘플 소스 코드를 설정합니다.

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

python HelloAnalytics.py

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

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

문제 해결

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

이 오류는 pip가 설치된 모듈보다 먼저 'six' 모듈 (이 라이브러리의 종속 항목)의 기본 설치가 로드되는 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