LoginSignup
3
3

More than 5 years have passed since last update.

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

Posted at

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

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

認証情報で承認済みリダイレクトURLの認証が必要
スクリーンショット 2016-11-28 午後5.36.55.png

作成後JSONデータをダウンロード
スクリーンショット 2016-11-28 午後5.39.12.png

サンプル
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)

アカウント認証がされるので任意アカウント選択
スクリーンショット 2016-11-28 午後5.42.16.png

承認済みリダイレクト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()
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3