teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

書式の改善

2017/09/13 08:01

投稿

k7_pgms88
k7_pgms88

スコア8

title CHANGED
@@ -1,1 +1,1 @@
1
- 【Googleアナリティクス Reporting API 】Pageviewが0だとレスポンスに含まれない
1
+ 【Googleアナリティクス Reporting API 】データが0の時、レスポンスに含まれない
body CHANGED
@@ -1,59 +1,36 @@
1
1
  GoogleアナリティクスのReporting API v4を利用し分間のPV数を取得するとき、
2
- 数値が0の場合は、レスポンスに含まれないようなのですが、
2
+ 数値が0の場合は、dimensionsがレスポンスに含まれないようなのですが、
3
3
 
4
4
  レスポンスにpvが0でも含まれるようにすることはできるのでしょうか?
5
5
  それとも、そもそも含まれるようにすることはできないのでしょうか?
6
6
 
7
+ 例)
7
- また、コードはGoogleサンプルにあったものを利用しています。
8
+ 2017-09-11 11:01とき、pageview「2」
8
-
9
+ 2017-09-11 11:02のとき、pageview「0」
10
+ 2017-09-11 11:03のとき、pageview「1」
11
+ の時、レスポンスは
9
12
  ```ここに言語を入力
13
+ 'data': {
14
+ 'rows': [{
10
- """Hello Analytics Reporting API V4."""
15
+ 'dimensions': ['201709111101'],
16
+ 'metrics': [{
17
+ 'values': ['2']
18
+ }]
19
+ }, {
20
+ 'dimensions': ['201709111103'],
21
+ 'metrics': [{
22
+ 'values': ['1']
23
+ }]
24
+ }
25
+ }
26
+ ```
27
+ 上記のように2017-09-11 11:02のデータがレポンスに含まれません。
11
28
 
12
- import argparse
13
29
 
14
- from apiclient.discovery import build
30
+ また、コードはGoogleのサンプルにあったものを利用しており、実際のコードは
15
- import httplib2
31
+ 下記のようにしています。
16
- from oauth2client import client
17
- from oauth2client import file
18
- from oauth2client import tools
19
32
 
20
- SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
21
- DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest')
22
- CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file.
23
- VIEW_ID = '<REPLACE_WITH_VIEW_ID>'
24
-
25
- def initialize_analyticsreporting():
26
- """Initializes the analyticsreporting service object.
27
-
28
- Returns:
33
+ ```ここに言語を入力
29
- analytics an authorized analyticsreporting service object.
30
- """
31
- # Parse command-line arguments.
32
- parser = argparse.ArgumentParser(
33
- formatter_class=argparse.RawDescriptionHelpFormatter,
34
- parents=[tools.argparser])
35
- flags = parser.parse_args([])
36
-
37
- # Set up a Flow object to be used if we need to authenticate.
38
- flow = client.flow_from_clientsecrets(
39
- CLIENT_SECRETS_PATH, scope=SCOPES,
40
- message=tools.message_if_missing(CLIENT_SECRETS_PATH))
41
-
42
- # Prepare credentials, and authorize HTTP object with them.
43
- # If the credentials don't exist or are invalid run through the native client
44
- # flow. The Storage object will ensure that if successful the good
45
- # credentials will get written back to a file.
46
- storage = file.Storage('analyticsreporting.dat')
47
- credentials = storage.get()
48
- if credentials is None or credentials.invalid:
49
- credentials = tools.run_flow(flow, storage, flags)
50
- http = credentials.authorize(http=httplib2.Http())
51
-
52
- # Build the service object.
53
- analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI)
54
-
55
- return analytics
56
-
57
34
  def get_report(analytics):
58
35
  # Use the Analytics Service Object to query the Analytics Reporting API V4.
59
36
  return analytics.reports().batchGet(
@@ -61,39 +38,11 @@
61
38
  'reportRequests': [
62
39
  {
63
40
  'viewId': VIEW_ID,
41
+ 'pageSize': 10000,
64
- 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}],
42
+ 'dateRanges': [{'startDate': '2017-09-11', 'endDate': '2017-09-11'}],
43
+ 'dimensions':[{'name':'ga:dateHourMinute'}],
65
44
  'metrics': [{'expression': 'ga:pageviews'}]
66
45
  }]
67
46
  }
68
47
  ).execute()
69
-
70
- def print_response(response):
71
- """Parses and prints the Analytics Reporting API V4 response"""
72
-
73
- for report in response.get('reports', []):
74
- columnHeader = report.get('columnHeader', {})
75
- dimensionHeaders = columnHeader.get('dimensions', [])
76
- metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
77
- rows = report.get('data', {}).get('rows', [])
78
-
79
- for row in rows:
80
- dimensions = row.get('dimensions', [])
81
- dateRangeValues = row.get('metrics', [])
82
-
83
- for header, dimension in zip(dimensionHeaders, dimensions):
84
- print header + ': ' + dimension
85
-
86
- for i, values in enumerate(dateRangeValues):
87
- print 'Date range (' + str(i) + ')'
88
- for metricHeader, value in zip(metricHeaders, values.get('values')):
89
- print metricHeader.get('name') + ': ' + value
90
-
91
- def main():
92
-
93
- analytics = initialize_analyticsreporting()
94
- response = get_report(analytics)
95
- print_response(response)
96
-
97
- if __name__ == '__main__':
98
- main()
99
48
  ```