Google API Client for pythonでアナリティクス APIからデータ取得その2 webアプリケーション編


前回はCLIだったので今回はWebアプリ編

リファレンス
https://developers.google.com/api-client-library/python/auth/web-app

認証情報で承認済みリダイレクトURLの認証が必要

作成後JSONデータをダウンロード

サンプル
djangoを使用しているので、HttpResponseRedirectを利用

from oauth2client import client
from django.http import HttpResponseRedirect

flow = client.flow_from_clientsecrets(
    'client_secrets.json',
    scope='https://www.googleapis.com/auth/drive.metadata.readonly',
    redirect_uri='http://www.example.com/oauth2callback')

auth_uri = flow.step1_get_authorize_url()
return HttpResponseRedirect(auth_uri)

アカウント認証がされるので任意アカウント選択

承認済みリダイレクトURLで認証codeが取得できるのでそれを使用しアナリティクスデータ取得

auth_code = request.GET['code']
flow = client.flow_from_clientsecrets(
    'client_secrets.json',
    scope='https://www.googleapis.com/auth/drive.metadata.readonly',
    redirect_uri='http://www.example.com/oauth2callback')
credentials = flow.step2_exchange(auth_code)
http_auth = credentials.authorize(httplib2.Http())
analytics = build('analytics', 'v4', http=http_auth, discoveryServiceUrl=self.DISCOVERY_URI)
reports = analytics.reports()
reports.batchGet(
                body={
                    'reportRequests': [
                        {
                            'viewId': self.VIEW_ID,
                            'dateRanges': [{'startDate': self.target_date, 'endDate': 'today'}],
                            "dimensions": [
                                {
                                    "name": "ga:productSku",  # 販売した品目の商品コードです。
                                }],
                            'metrics': [
                                {'expression': 'ga:itemQuantity'}  # e コマース トランザクションで売れた商品の数です。
                            ],
                            'pageSize': 50000,
                            'pageToken': "nextpage",
                            "orderBys":
                                [
                                    {"fieldName": "ga:itemQuantity", "sortOrder": "DESCENDING"},
                                ]
                        }]
                }
        ).execute()