이 튜토리얼에서는 Analytics Reporting API v4에 액세스하는 데 필요한 단계를 안내합니다.
1. API 사용 설정
Analytics Reporting API v4를 사용하려면 먼저 설정 도구를 사용해야 합니다. 이 도구는 Google API 콘솔에서 프로젝트를 만들고, API를 사용 설정하고, 사용자 인증 정보를 만드는 방법을 안내합니다.
참고: 웹 클라이언트 ID 또는 설치된 애플리케이션 클라이언트를 생성하려면 동의 화면에서 제품 이름을 설정해야 합니다. 아직 동의 화면을 구성하지 않았다면 동의 화면 구성 메시지가 표시됩니다.사용자 인증 정보 만들기
- 사용자 인증 정보 페이지를 엽니다.
- 사용자 인증 정보 만들기를 클릭하고 OAuth 클라이언트 ID를 선택합니다.
- 애플리케이션 유형으로 기타를 선택합니다.
- 클라이언트 ID의 이름을 quickstart로 지정하고 만들기를 클릭합니다.
사용자 인증 정보 페이지에서 새로 생성된 클라이언트 ID를 클릭하고 JSON 다운로드를 클릭하여 client_secrets.json
로 저장합니다. 이 ID는 튜토리얼의 후반부에서 필요합니다.
2. 클라이언트 라이브러리 설치하기
Python 패키지를 설치할 때 pip를 venv와 함께 사용하는 것이 좋습니다. 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
라는 단일 파일을 만들어야 합니다.
- 다음 소스 코드를
HelloAnalytics.py
로 복사하거나 다운로드합니다. - 이전에 다운로드한
client_secrets.json
를 샘플 코드와 동일한 디렉터리로 이동합니다. 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' 객체에 'urlparse' 속성이 없음
이 오류는 pip가 설치된 모듈보다 먼저 "six" 모듈의 기본 설치 (이 라이브러리의 종속 항목)가 로드되는 Mac OSX에서 발생할 수 있습니다. 이 문제를 해결하려면 pip의 설치 위치를 PYTHONPATH
시스템 환경 변수에 추가합니다.
다음 명령어를 사용하여 pip의 설치 위치를 확인합니다.
pip show6 | grep "위치:" | cut -d " " -f2
~/.bashrc
파일에 다음 줄을 추가하고<pip_install_path>
을 위에서 결정된 값으로 바꿉니다.export PYTHONPATH=$PYTHONPATH:<pip_install_path>
다음 명령어를 사용하여 열려 있는 터미널 창에서
~/.bashrc
파일을 새로고침합니다.소스 ~/.bashrc