LEFT | RIGHT |
1 #!/usr/bin/python | 1 #!/usr/bin/python |
2 # -*- coding: utf-8 -*- | 2 # -*- coding: utf-8 -*- |
3 # | 3 # |
4 # Copyright 2012 Google Inc. All Rights Reserved. | 4 # Copyright 2012 Google Inc. All Rights Reserved. |
5 # | 5 # |
6 # Licensed under the Apache License, Version 2.0 (the "License"); | 6 # Licensed under the Apache License, Version 2.0 (the "License"); |
7 # you may not use this file except in compliance with the License. | 7 # you may not use this file except in compliance with the License. |
8 # You may obtain a copy of the License at | 8 # You may obtain a copy of the License at |
9 # | 9 # |
10 # http://www.apache.org/licenses/LICENSE-2.0 | 10 # http://www.apache.org/licenses/LICENSE-2.0 |
11 # | 11 # |
12 # Unless required by applicable law or agreed to in writing, software | 12 # Unless required by applicable law or agreed to in writing, software |
13 # distributed under the License is distributed on an "AS IS" BASIS, | 13 # distributed under the License is distributed on an "AS IS" BASIS, |
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15 # See the License for the specific language governing permissions and | 15 # See the License for the specific language governing permissions and |
16 # limitations under the License. | 16 # limitations under the License. |
17 | 17 |
18 """Reference command-line example for Google Analytics Core Reporting API v3. | 18 """Reference command-line example for Google Analytics Core Reporting API v3. |
19 | 19 |
20 This application demonstrates how to use the python client library to access | 20 This application demonstrates how to use the python client library to access |
21 all the pieces of data returned by the Google Analytics Core Reporting API v3. | 21 all the pieces of data returned by the Google Analytics Core Reporting API v3. |
22 | 22 |
23 The application manages autorization by saving an OAuth2.0 token in a local | 23 The application manages autorization by saving an OAuth2.0 token in a local |
24 file and reusing the token for subsequent requests. | 24 file and reusing the token for subsequent requests. |
25 | 25 |
26 Before you begin: | 26 Before You Begin: |
27 | 27 |
28 You must update the client_secrets.json file with a client id, client secret, | 28 Update the client_secrets.json file |
29 and the redirect uri. You get these values by creating a new project | 29 |
30 in the Google APIs console and registering for OAuth2.0 for installed | 30 You must update the clients_secrets.json file with a client id, client |
31 applications: https://code.google.com/apis/console | 31 secret, and the redirect uri. You get these values by creating a new project |
32 | 32 in the Google APIs console and registering for OAuth2.0 for installed |
33 Learn more about registering your Analytics Application here: | 33 applications: https://code.google.com/apis/console |
34 http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html | 34 |
35 | 35 Learn more about registering your analytics application here: |
36 You will also need to identify from which profile to access data by specifying | 36 http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html |
37 the TABLE_ID constant below. This value is of the form: ga:xxxx where xxxx | 37 |
38 is the profile ID. You can get the profile ID by either querying the Management | 38 Supply your TABLE_ID |
39 API or by looking it up in the account settings of the web interface. | 39 |
| 40 You will also need to identify from which profile to access data by |
| 41 specifying the TABLE_ID constant below. This value is of the form: ga:xxxx |
| 42 where xxxx is the profile ID. You can get the profile ID by either querying |
| 43 the Management API or by looking it up in the account settings of the |
| 44 Google Anlaytics web interface. |
40 | 45 |
41 Sample Usage: | 46 Sample Usage: |
42 | 47 |
43 $ python data_v3_reference.py | 48 $ python core_reporting_v3_reference.py |
44 | 49 |
45 Also you can also get help on all the command-line flags the program | 50 Also you can also get help on all the command-line flags the program |
46 understands by running: | 51 understands by running: |
47 | 52 |
48 $ python data_v3_reference.py --help | 53 $ python core_reporting_v3_reference.py --help |
49 """ | 54 """ |
50 | 55 |
51 __author__ = 'api.nickm@ (Nick Mihailovski)' | 56 __author__ = 'api.nickm@gmail.com (Nick Mihailovski)' |
52 | 57 |
53 import sys | 58 import sys |
54 | 59 import sample_utils |
55 from apiclient.discovery import build | 60 |
56 from apiclient.errors import HttpError | 61 from apiclient.errors import HttpError |
57 | |
58 import gflags | |
59 import httplib2 | |
60 | |
61 from oauth2client.client import AccessTokenRefreshError | 62 from oauth2client.client import AccessTokenRefreshError |
62 from oauth2client.client import flow_from_clientsecrets | 63 |
63 from oauth2client.anyjson import simplejson | 64 |
64 from oauth2client.file import Storage | 65 # The table ID is used to identify from which Google Anlaytics profile |
65 from oauth2client.tools import run | 66 # to retrieve data. This ID is in the format ga:xxxx where xxxx is the |
66 | 67 # profile ID. |
67 FLAGS = gflags.FLAGS | |
68 | |
69 | |
70 # Remember to get your own client_id / client_secret in the | |
71 # Google API developer console: https://code.google.com/apis/console | |
72 FLOW = flow_from_clientsecrets('client_secrets.json', | |
73 scope='https://www.googleapis.com/auth/analytics.readonly') | |
74 | |
75 | |
76 # Name of file that will store the access and refresh tokens to access | |
77 # the API without having to login each time. Make sure this file is in | |
78 # a secure place. | |
79 TOKEN_FILE_NAME = 'analytics.dat' | |
80 | |
81 | |
82 # This has the format ga:xxx where xxx is the profile id. | |
83 TABLE_ID = 'INSERT_YOUR_TABLE_ID_HERE' | 68 TABLE_ID = 'INSERT_YOUR_TABLE_ID_HERE' |
84 | 69 |
85 | 70 |
86 def main(argv): | 71 def main(argv): |
87 # Let the gflags module process the command-line arguments | 72 sample_utils.process_flags(argv) |
88 try: | 73 |
89 argv = FLAGS(argv) | 74 # Authenticate and construct service. |
90 except gflags.FlagsError, e: | 75 service = sample_utils.initialize_service() |
91 print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS) | |
92 sys.exit(1) | |
93 | |
94 # Manage authorization tokens. Either use an existing one or get a new one. | |
95 storage = Storage(TOKEN_FILE_NAME) | |
96 credentials = storage.get() | |
97 if not credentials or credentials.invalid: | |
98 # Get a new token. | |
99 credentials = run(FLOW, storage) | |
100 | |
101 # Build an authorized service object to work with the API. | |
102 http = httplib2.Http() | |
103 http = credentials.authorize(http) | |
104 service = build('analytics', 'v3', http=http) | |
105 | 76 |
106 # Try to make a request to the API. Print the results or handle errors. | 77 # Try to make a request to the API. Print the results or handle errors. |
107 try: | 78 try: |
108 results = get_api_query(service).execute() | 79 results = get_api_query(service).execute() |
109 print_results(results) | 80 print_results(results) |
110 | 81 |
| 82 except TypeError, error: |
| 83 # Handle errors in constructing a query. |
| 84 print ('There was an error in constructing your query : %s' % error) |
| 85 |
111 except HttpError, error: | 86 except HttpError, error: |
112 # Handle API errors. | 87 # Handle API errors. |
113 print ('Arg, there was an API error : %s %s : %s' % | 88 print ('Arg, there was an API error : %s : %s' % |
114 (error.resp.status, error.resp.reason, error._get_reason())) | 89 (error.resp.status, error._get_reason())) |
115 | |
116 print 'Detailed Error Infos:' | |
117 json_error = simplejson.loads(error.content) | |
118 print json_error | |
119 for e in json_error.get('error').get('errors'): | |
120 print '\t%s : %s' % (e.get('message'), e.get('debugInfo')) | |
121 print | |
122 | 90 |
123 except AccessTokenRefreshError: | 91 except AccessTokenRefreshError: |
124 # Handle Auth errors. | 92 # Handle Auth errors. |
125 print ('The credentials have been revoked or expired, please re-run ' | 93 print ('The credentials have been revoked or expired, please re-run ' |
126 'the application to re-authorize') | 94 'the application to re-authorize') |
127 | 95 |
128 | 96 |
129 def get_api_query(service): | 97 def get_api_query(service): |
130 """Returns a query object to retrieve data from the data export API. | 98 """Returns a query object to retrieve data from the Core Reporting API. |
131 | 99 |
132 Args: | 100 Args: |
133 service: The service object built by the Google API Python client library. | 101 service: The service object built by the Google API Python client library. |
134 """ | 102 """ |
135 | 103 |
136 return service.data().ga().get( | 104 return service.data().ga().get( |
137 ids=TABLE_ID, | 105 ids=TABLE_ID, |
138 start_date='2012-01-01', | 106 start_date='2012-01-01', |
139 end_date='2012-01-15', | 107 end_date='2012-01-15', |
140 metrics='ga:visits', | 108 metrics='ga:visits', |
(...skipping 128 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
269 | 237 |
270 | 238 |
271 def print_rows(results): | 239 def print_rows(results): |
272 """Prints all the rows of data returned by the API. | 240 """Prints all the rows of data returned by the API. |
273 | 241 |
274 Args: | 242 Args: |
275 results: The response returned from the Core Reporting API. | 243 results: The response returned from the Core Reporting API. |
276 """ | 244 """ |
277 | 245 |
278 print 'Rows:' | 246 print 'Rows:' |
279 if results.get('rows'): | 247 if results.get('rows', []): |
280 for row in results.get('rows'): | 248 for row in results.get('rows'): |
281 print '\t'.join(row) | 249 print '\t'.join(row) |
282 else: | 250 else: |
283 print 'No Rows Found' | 251 print 'No Rows Found' |
284 | 252 |
285 | 253 |
286 if __name__ == '__main__': | 254 if __name__ == '__main__': |
287 main(sys.argv) | 255 main(sys.argv) |
LEFT | RIGHT |