LoginSignup
3
3

More than 5 years have passed since last update.

Google API Client for pythonでアナリティクス APIからデータ取得

Last updated at Posted at 2016-11-28

リファレンス
https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/installed-py

サンプルclass

class GoogleAnalyticsUtility(object):
    SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
    DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')
    VIEW_ID = 'xxxx'

    def __init__(self, target_date):
        self.target_date = target_date

    def get_report(self):
        parser = argparse.ArgumentParser(
                formatter_class=argparse.RawDescriptionHelpFormatter,
                parents=[tools.argparser])
        flags = parser.parse_args(['--noauth_local_webserver'])
        CLIENT_SECRETS_PATH = os.path.join(settings.BASE_DIR, '../etc/googleapi/client_id.json')
        flow = client.flow_from_clientsecrets(
                CLIENT_SECRETS_PATH, scope=self.SCOPES,
                message=tools.message_if_missing(CLIENT_SECRETS_PATH))

        storage = file.Storage(os.path.join(settings.BASE_DIR, '../etc/googleapi/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())
        analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=self.DISCOVERY_URI)
        reports = analytics.reports()
        return 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()

target_date = date.today() - timedelta(days=7)
ga = GoogleAnalyticsUtility(target_date.strftime('%Y-%m-%d'))
ga.get_report()

コマンドラインで叩いた場合,リンクが表示されるのでこれをコピペしてブラウザに貼り付ければ認証完了

https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id=xxxxx-gd5j31ge4jdobhlg9a3jqnveae34cag1.apps.googleusercontent.com&access_type=offline

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