new analytics api samples. Reviewed here: http://codereview.appspot.com/5494058/
Fixes issue #5494058
This commit is contained in:
9
samples/analytics/client_secrets.json
Normal file
9
samples/analytics/client_secrets.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"installed": {
|
||||||
|
"client_id": "[[INSERT CLIENT ID HERE]]",
|
||||||
|
"client_secret": "[[INSERT CLIENT SECRET HERE]]",
|
||||||
|
"redirect_uris": [],
|
||||||
|
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
||||||
|
"token_uri": "https://accounts.google.com/o/oauth2/token"
|
||||||
|
}
|
||||||
|
}
|
||||||
255
samples/analytics/core_reporting_v3_reference.py
Executable file
255
samples/analytics/core_reporting_v3_reference.py
Executable file
@@ -0,0 +1,255 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright 2012 Google Inc. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
"""Reference command-line example for Google Analytics Core Reporting API v3.
|
||||||
|
|
||||||
|
This application demonstrates how to use the python client library to access
|
||||||
|
all the pieces of data returned by the Google Analytics Core Reporting API v3.
|
||||||
|
|
||||||
|
The application manages autorization by saving an OAuth2.0 token in a local
|
||||||
|
file and reusing the token for subsequent requests.
|
||||||
|
|
||||||
|
Before You Begin:
|
||||||
|
|
||||||
|
Update the client_secrets.json file
|
||||||
|
|
||||||
|
You must update the clients_secrets.json file with a client id, client
|
||||||
|
secret, and the redirect uri. You get these values by creating a new project
|
||||||
|
in the Google APIs console and registering for OAuth2.0 for installed
|
||||||
|
applications: https://code.google.com/apis/console
|
||||||
|
|
||||||
|
Learn more about registering your analytics application here:
|
||||||
|
http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html
|
||||||
|
|
||||||
|
Supply your TABLE_ID
|
||||||
|
|
||||||
|
You will also need to identify from which profile to access data by
|
||||||
|
specifying the TABLE_ID constant below. This value is of the form: ga:xxxx
|
||||||
|
where xxxx is the profile ID. You can get the profile ID by either querying
|
||||||
|
the Management API or by looking it up in the account settings of the
|
||||||
|
Google Anlaytics web interface.
|
||||||
|
|
||||||
|
Sample Usage:
|
||||||
|
|
||||||
|
$ python core_reporting_v3_reference.py
|
||||||
|
|
||||||
|
Also you can also get help on all the command-line flags the program
|
||||||
|
understands by running:
|
||||||
|
|
||||||
|
$ python core_reporting_v3_reference.py --help
|
||||||
|
"""
|
||||||
|
|
||||||
|
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import sample_utils
|
||||||
|
|
||||||
|
from apiclient.errors import HttpError
|
||||||
|
from oauth2client.client import AccessTokenRefreshError
|
||||||
|
|
||||||
|
|
||||||
|
# The table ID is used to identify from which Google Anlaytics profile
|
||||||
|
# to retrieve data. This ID is in the format ga:xxxx where xxxx is the
|
||||||
|
# profile ID.
|
||||||
|
TABLE_ID = 'INSERT_YOUR_TABLE_ID_HERE'
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
sample_utils.process_flags(argv)
|
||||||
|
|
||||||
|
# Authenticate and construct service.
|
||||||
|
service = sample_utils.initialize_service()
|
||||||
|
|
||||||
|
# Try to make a request to the API. Print the results or handle errors.
|
||||||
|
try:
|
||||||
|
results = get_api_query(service).execute()
|
||||||
|
print_results(results)
|
||||||
|
|
||||||
|
except TypeError, error:
|
||||||
|
# Handle errors in constructing a query.
|
||||||
|
print ('There was an error in constructing your query : %s' % error)
|
||||||
|
|
||||||
|
except HttpError, error:
|
||||||
|
# Handle API errors.
|
||||||
|
print ('Arg, there was an API error : %s : %s' %
|
||||||
|
(error.resp.status, error._get_reason()))
|
||||||
|
|
||||||
|
except AccessTokenRefreshError:
|
||||||
|
# Handle Auth errors.
|
||||||
|
print ('The credentials have been revoked or expired, please re-run '
|
||||||
|
'the application to re-authorize')
|
||||||
|
|
||||||
|
|
||||||
|
def get_api_query(service):
|
||||||
|
"""Returns a query object to retrieve data from the Core Reporting API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
service: The service object built by the Google API Python client library.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return service.data().ga().get(
|
||||||
|
ids=TABLE_ID,
|
||||||
|
start_date='2012-01-01',
|
||||||
|
end_date='2012-01-15',
|
||||||
|
metrics='ga:visits',
|
||||||
|
dimensions='ga:source,ga:keyword',
|
||||||
|
sort='-ga:visits',
|
||||||
|
filters='ga:medium==organic',
|
||||||
|
start_index='1',
|
||||||
|
max_results='25')
|
||||||
|
|
||||||
|
|
||||||
|
def print_results(results):
|
||||||
|
"""Prints all the results in the Core Reporting API Response.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print_report_info(results)
|
||||||
|
print_pagination_info(results)
|
||||||
|
print_profile_info(results)
|
||||||
|
print_query(results)
|
||||||
|
print_column_headers(results)
|
||||||
|
print_totals_for_all_results(results)
|
||||||
|
print_rows(results)
|
||||||
|
|
||||||
|
|
||||||
|
def print_report_info(results):
|
||||||
|
"""Prints general information about this report.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print 'Report Infos:'
|
||||||
|
print 'Contains Sampled Data = %s' % results.get('containsSampledData')
|
||||||
|
print 'Kind = %s' % results.get('kind')
|
||||||
|
print 'ID = %s' % results.get('id')
|
||||||
|
print 'Self Link = %s' % results.get('selfLink')
|
||||||
|
print
|
||||||
|
|
||||||
|
|
||||||
|
def print_pagination_info(results):
|
||||||
|
"""Prints common pagination details.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print 'Pagination Infos:'
|
||||||
|
print 'Items per page = %s' % results.get('itemsPerPage')
|
||||||
|
print 'Total Results = %s' % results.get('totalResults')
|
||||||
|
|
||||||
|
# These only have values if other result pages exist.
|
||||||
|
if results.get('previousLink'):
|
||||||
|
print 'Previous Link = %s' % results.get('previousLink')
|
||||||
|
if results.get('nextLink'):
|
||||||
|
print 'Next Link = %s' % results.get('nextLink')
|
||||||
|
print
|
||||||
|
|
||||||
|
|
||||||
|
def print_profile_info(results):
|
||||||
|
"""Prints information about the profile.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print 'Profile Infos:'
|
||||||
|
info = results.get('profileInfo')
|
||||||
|
print 'Account Id = %s' % info.get('accountId')
|
||||||
|
print 'Web Property Id = %s' % info.get('webPropertyId')
|
||||||
|
print 'Profile Id = %s' % info.get('profileId')
|
||||||
|
print 'Table Id = %s' % info.get('tableId')
|
||||||
|
print 'Profile Name = %s' % info.get('profileName')
|
||||||
|
print
|
||||||
|
|
||||||
|
|
||||||
|
def print_query(results):
|
||||||
|
"""The query returns the original report query as a dict.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print 'Query Parameters:'
|
||||||
|
query = results.get('query')
|
||||||
|
for key, value in query.iteritems():
|
||||||
|
print '%s = %s' % (key, value)
|
||||||
|
print
|
||||||
|
|
||||||
|
|
||||||
|
def print_column_headers(results):
|
||||||
|
"""Prints the information for each column.
|
||||||
|
|
||||||
|
The main data from the API is returned as rows of data. The column
|
||||||
|
headers describe the names and types of each column in rows.
|
||||||
|
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print 'Column Headers:'
|
||||||
|
headers = results.get('columnHeaders')
|
||||||
|
for header in headers:
|
||||||
|
# Print Dimension or Metric name.
|
||||||
|
print '\t%s name: = %s' % (header.get('columnType').title(),
|
||||||
|
header.get('name'))
|
||||||
|
print '\tColumn Type = %s' % header.get('columnType')
|
||||||
|
print '\tData Type = %s' % header.get('dataType')
|
||||||
|
print
|
||||||
|
|
||||||
|
|
||||||
|
def print_totals_for_all_results(results):
|
||||||
|
"""Prints the total metric value for all pages the query matched.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print 'Total Metrics For All Results:'
|
||||||
|
print 'This query returned %s rows.' % len(results.get('rows'))
|
||||||
|
print ('But the query matched %s total results.' %
|
||||||
|
results.get('totalResults'))
|
||||||
|
print 'Here are the metric totals for the matched total results.'
|
||||||
|
totals = results.get('totalsForAllResults')
|
||||||
|
|
||||||
|
for metric_name, metric_total in totals.iteritems():
|
||||||
|
print 'Metric Name = %s' % metric_name
|
||||||
|
print 'Metric Total = %s' % metric_total
|
||||||
|
print
|
||||||
|
|
||||||
|
|
||||||
|
def print_rows(results):
|
||||||
|
"""Prints all the rows of data returned by the API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print 'Rows:'
|
||||||
|
if results.get('rows', []):
|
||||||
|
for row in results.get('rows'):
|
||||||
|
print '\t'.join(row)
|
||||||
|
else:
|
||||||
|
print 'No Rows Found'
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main(sys.argv)
|
||||||
176
samples/analytics/hello_analytics_api_v3.py
Executable file
176
samples/analytics/hello_analytics_api_v3.py
Executable file
@@ -0,0 +1,176 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright 2012 Google Inc. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
"""Simple intro to using the Google Analytics API v3.
|
||||||
|
|
||||||
|
This application demonstrates how to use the python client library to access
|
||||||
|
Google Analytics data. The sample traverses the Management API to obtain the
|
||||||
|
authorized user's first profile ID. Then the sample uses this ID to
|
||||||
|
contstruct a Core Reporting API query to return the top 25 organic search
|
||||||
|
terms.
|
||||||
|
|
||||||
|
Before you begin, you must sigup for a new project in the Google APIs console:
|
||||||
|
https://code.google.com/apis/console
|
||||||
|
|
||||||
|
Then register the project to use OAuth2.0 for installed applications.
|
||||||
|
|
||||||
|
Finally you will need to add the client id, client secret, and redirect URL
|
||||||
|
into the client_secrets.json file that is in the same directory as this sample.
|
||||||
|
|
||||||
|
Sample Usage:
|
||||||
|
|
||||||
|
$ python hello_analytics_api_v3.py
|
||||||
|
|
||||||
|
Also you can also get help on all the command-line flags the program
|
||||||
|
understands by running:
|
||||||
|
|
||||||
|
$ python hello_analytics_api_v3.py --help
|
||||||
|
"""
|
||||||
|
|
||||||
|
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import sample_utils
|
||||||
|
|
||||||
|
from apiclient.errors import HttpError
|
||||||
|
from oauth2client.client import AccessTokenRefreshError
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
sample_utils.process_flags(argv)
|
||||||
|
|
||||||
|
# Authenticate and construct service.
|
||||||
|
service = sample_utils.initialize_service()
|
||||||
|
|
||||||
|
# Try to make a request to the API. Print the results or handle errors.
|
||||||
|
try:
|
||||||
|
first_profile_id = get_first_profile_id(service)
|
||||||
|
if not first_profile_id:
|
||||||
|
print 'Could not find a valid profile for this user.'
|
||||||
|
else:
|
||||||
|
results = get_top_keywords(service, first_profile_id)
|
||||||
|
print_results(results)
|
||||||
|
|
||||||
|
except TypeError, error:
|
||||||
|
# Handle errors in constructing a query.
|
||||||
|
print ('There was an error in constructing your query : %s' % error)
|
||||||
|
|
||||||
|
except HttpError, error:
|
||||||
|
# Handle API errors.
|
||||||
|
print ('Arg, there was an API error : %s : %s' %
|
||||||
|
(error.resp.status, error._get_reason()))
|
||||||
|
|
||||||
|
except AccessTokenRefreshError:
|
||||||
|
# Handle Auth errors.
|
||||||
|
print ('The credentials have been revoked or expired, please re-run '
|
||||||
|
'the application to re-authorize')
|
||||||
|
|
||||||
|
|
||||||
|
def get_first_profile_id(service):
|
||||||
|
"""Traverses Management API to return the first profile id.
|
||||||
|
|
||||||
|
This first queries the Accounts collection to get the first account ID.
|
||||||
|
This ID is used to query the Webproperties collection to retrieve the first
|
||||||
|
webproperty ID. And both account and webproperty IDs are used to query the
|
||||||
|
Profile collection to get the first profile id.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
service: The service object built by the Google API Python client library.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A string with the first profile ID. None if a user does not have any
|
||||||
|
accounts, webproperties, or profiles.
|
||||||
|
"""
|
||||||
|
|
||||||
|
accounts = service.management().accounts().list().execute()
|
||||||
|
|
||||||
|
if accounts.get('items'):
|
||||||
|
firstAccountId = accounts.get('items')[0].get('id')
|
||||||
|
webproperties = service.management().webproperties().list(
|
||||||
|
accountId=firstAccountId).execute()
|
||||||
|
|
||||||
|
if webproperties.get('items'):
|
||||||
|
firstWebpropertyId = webproperties.get('items')[0].get('id')
|
||||||
|
profiles = service.management().profiles().list(
|
||||||
|
accountId=firstAccountId,
|
||||||
|
webPropertyId=firstWebpropertyId).execute()
|
||||||
|
|
||||||
|
if profiles.get('items'):
|
||||||
|
return profiles.get('items')[0].get('id')
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_top_keywords(service, profile_id):
|
||||||
|
"""Executes and returns data from the Core Reporting API.
|
||||||
|
|
||||||
|
This queries the API for the top 25 organic search terms by visits.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
service: The service object built by the Google API Python client library.
|
||||||
|
profile_id: String The profile ID from which to retrieve analytics data.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return service.data().ga().get(
|
||||||
|
ids='ga:' + profile_id,
|
||||||
|
start_date='2012-01-01',
|
||||||
|
end_date='2012-01-15',
|
||||||
|
metrics='ga:visits',
|
||||||
|
dimensions='ga:source,ga:keyword',
|
||||||
|
sort='-ga:visits',
|
||||||
|
filters='ga:medium==organic',
|
||||||
|
start_index='1',
|
||||||
|
max_results='25').execute()
|
||||||
|
|
||||||
|
|
||||||
|
def print_results(results):
|
||||||
|
"""Prints out the results.
|
||||||
|
|
||||||
|
This prints out the profile name, the column headers, and all the rows of
|
||||||
|
data.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
results: The response returned from the Core Reporting API.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print
|
||||||
|
print 'Profile Name: %s' % results.get('profileInfo').get('profileName')
|
||||||
|
print
|
||||||
|
|
||||||
|
# Print header.
|
||||||
|
output = []
|
||||||
|
for header in results.get('columnHeaders'):
|
||||||
|
output.append('%30s' % header.get('name'))
|
||||||
|
print ''.join(output)
|
||||||
|
|
||||||
|
# Print data table.
|
||||||
|
if results.get('rows', []):
|
||||||
|
for row in results.get('rows'):
|
||||||
|
output = []
|
||||||
|
for cell in row:
|
||||||
|
output.append('%30s' % cell)
|
||||||
|
print ''.join(output)
|
||||||
|
|
||||||
|
else:
|
||||||
|
print 'No Rows Found'
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main(sys.argv)
|
||||||
563
samples/analytics/management_v3_reference.py
Normal file → Executable file
563
samples/analytics/management_v3_reference.py
Normal file → Executable file
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/python
|
#!/usr/bin/python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
#
|
#
|
||||||
# Copyright 2011 Google Inc. All Rights Reserved.
|
# Copyright 2012 Google Inc. All Rights Reserved.
|
||||||
#
|
#
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
@@ -32,79 +32,55 @@ To read an indepth discussion on how this file works, check out the Management
|
|||||||
API Python Getting Started guide here:
|
API Python Getting Started guide here:
|
||||||
http://code.google.com/apis/analytics/docs/mgmt/v3/mgmtPython.html
|
http://code.google.com/apis/analytics/docs/mgmt/v3/mgmtPython.html
|
||||||
|
|
||||||
Usage:
|
Before You Begin:
|
||||||
|
|
||||||
Before you begin, you should register your application as an installed
|
Update the client_secrets.json file
|
||||||
application to get your own Project / OAUth2 Client ID / Secret:
|
|
||||||
https://code.google.com/apis/console
|
|
||||||
|
|
||||||
Learn more about registering your Analytics Application here:
|
You must update the clients_secrets.json file with a client id, client
|
||||||
http://code.google.com/apis/analytics/docs/mgmt/v3/mgmtPython.html#authorize
|
secret, and the redirect uri. You get these values by creating a new project
|
||||||
|
in the Google APIs console and registering for OAuth2.0 for installed
|
||||||
|
applications: https://code.google.com/apis/console
|
||||||
|
|
||||||
$ python analytics.py
|
Learn more about registering your analytics application here:
|
||||||
|
http://code.google.com/apis/analytics/docs/gdata/v3/gdataAuthorization.html
|
||||||
|
|
||||||
|
Sample Usage:
|
||||||
|
|
||||||
|
$ python management_v3_reference.py
|
||||||
|
|
||||||
Also you can also get help on all the command-line flags the program
|
Also you can also get help on all the command-line flags the program
|
||||||
understands by running:
|
understands by running:
|
||||||
|
|
||||||
$ python analytics.py --help
|
$ python management_v3_reference.py --help
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__author__ = 'api.nickm@ (Nick Mihailovski)'
|
__author__ = 'api.nickm@gmail.com (Nick Mihailovski)'
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
|
import sample_utils
|
||||||
|
|
||||||
from apiclient.discovery import build
|
|
||||||
from apiclient.errors import HttpError
|
from apiclient.errors import HttpError
|
||||||
|
|
||||||
import gflags
|
|
||||||
import httplib2
|
|
||||||
|
|
||||||
from oauth2client.client import AccessTokenRefreshError
|
from oauth2client.client import AccessTokenRefreshError
|
||||||
from oauth2client.client import OAuth2WebServerFlow
|
|
||||||
from oauth2client.file import Storage
|
|
||||||
from oauth2client.tools import run
|
|
||||||
|
|
||||||
FLAGS = gflags.FLAGS
|
|
||||||
|
|
||||||
|
|
||||||
# Remember to get your own client_id / client_secret in the
|
|
||||||
# Google API developer console: https://code.google.com/apis/console
|
|
||||||
FLOW = OAuth2WebServerFlow(
|
|
||||||
client_id='INSERT_YOUR_CLIENT_ID_HERE',
|
|
||||||
client_secret='INSERT_YOUR_CLIENT_SECRET_HERE',
|
|
||||||
scope='https://www.googleapis.com/auth/analytics.readonly',
|
|
||||||
user_agent='analytics-api-v3-awesomeness')
|
|
||||||
|
|
||||||
TOKEN_FILE_NAME = 'analytics.dat'
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv):
|
def main(argv):
|
||||||
# Let the gflags module process the command-line arguments
|
sample_utils.process_flags(argv)
|
||||||
try:
|
|
||||||
argv = FLAGS(argv)
|
|
||||||
except gflags.FlagsError, e:
|
|
||||||
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
# Manage re-using tokens.
|
# Authenticate and construct service.
|
||||||
storage = Storage(TOKEN_FILE_NAME)
|
service = sample_utils.initialize_service()
|
||||||
credentials = storage.get()
|
|
||||||
if not credentials or credentials.invalid:
|
|
||||||
# Get a new token.
|
|
||||||
credentials = run(FLOW, storage)
|
|
||||||
|
|
||||||
# Build an authorized service object.
|
# Traverse the Management hiearchy and print results or handle errors.
|
||||||
http = httplib2.Http()
|
|
||||||
http = credentials.authorize(http)
|
|
||||||
service = build('analytics', 'v3', http=http)
|
|
||||||
|
|
||||||
# Traverse the Management hiearchy and print results.
|
|
||||||
try:
|
try:
|
||||||
traverse_hiearchy(service)
|
traverse_hiearchy(service)
|
||||||
|
|
||||||
|
except TypeError, error:
|
||||||
|
# Handle errors in constructing a query.
|
||||||
|
print ('There was an error in constructing your query : %s' % error)
|
||||||
|
|
||||||
except HttpError, error:
|
except HttpError, error:
|
||||||
print ('Arg, there was an API error : %s %s : %s' %
|
# Handle API errors.
|
||||||
(error.resp.status, error.resp.reason, error._get_reason()))
|
print ('Arg, there was an API error : %s : %s' %
|
||||||
|
(error.resp.status, error._get_reason()))
|
||||||
|
|
||||||
except AccessTokenRefreshError:
|
except AccessTokenRefreshError:
|
||||||
print ('The credentials have been revoked or expired, please re-run'
|
print ('The credentials have been revoked or expired, please re-run'
|
||||||
@@ -126,18 +102,16 @@ def traverse_hiearchy(service):
|
|||||||
HttpError: If an error occured when accessing the API.
|
HttpError: If an error occured when accessing the API.
|
||||||
AccessTokenRefreshError: If the current token was invalid.
|
AccessTokenRefreshError: If the current token was invalid.
|
||||||
"""
|
"""
|
||||||
view = View()
|
|
||||||
|
|
||||||
accounts = service.management().accounts().list().execute()
|
accounts = service.management().accounts().list().execute()
|
||||||
|
print_accounts(accounts)
|
||||||
view.print_accounts(accounts)
|
|
||||||
|
|
||||||
if accounts.get('items'):
|
if accounts.get('items'):
|
||||||
firstAccountId = accounts.get('items')[0].get('id')
|
firstAccountId = accounts.get('items')[0].get('id')
|
||||||
webproperties = service.management().webproperties().list(
|
webproperties = service.management().webproperties().list(
|
||||||
accountId=firstAccountId).execute()
|
accountId=firstAccountId).execute()
|
||||||
|
|
||||||
view.print_webproperties(webproperties)
|
print_webproperties(webproperties)
|
||||||
|
|
||||||
if webproperties.get('items'):
|
if webproperties.get('items'):
|
||||||
firstWebpropertyId = webproperties.get('items')[0].get('id')
|
firstWebpropertyId = webproperties.get('items')[0].get('id')
|
||||||
@@ -145,7 +119,7 @@ def traverse_hiearchy(service):
|
|||||||
accountId=firstAccountId,
|
accountId=firstAccountId,
|
||||||
webPropertyId=firstWebpropertyId).execute()
|
webPropertyId=firstWebpropertyId).execute()
|
||||||
|
|
||||||
view.print_profiles(profiles)
|
print_profiles(profiles)
|
||||||
|
|
||||||
if profiles.get('items'):
|
if profiles.get('items'):
|
||||||
firstProfileId = profiles.get('items')[0].get('id')
|
firstProfileId = profiles.get('items')[0].get('id')
|
||||||
@@ -154,226 +128,285 @@ def traverse_hiearchy(service):
|
|||||||
webPropertyId=firstWebpropertyId,
|
webPropertyId=firstWebpropertyId,
|
||||||
profileId=firstProfileId).execute()
|
profileId=firstProfileId).execute()
|
||||||
|
|
||||||
view.print_goals(goals)
|
print_goals(goals)
|
||||||
|
|
||||||
view.print_segments(service.management().segments().list().execute())
|
print_segments(service.management().segments().list().execute())
|
||||||
|
|
||||||
|
|
||||||
class View(object):
|
def print_accounts(accounts_response):
|
||||||
"""Utility class to print various Management API collections."""
|
"""Prints all the account info in the Accounts Collection.
|
||||||
|
|
||||||
def print_accounts(self, accounts_list):
|
Args:
|
||||||
"""Prints all the account info in the Accounts Collection."""
|
accounts_response: The response object returned from querying the Accounts
|
||||||
|
collection.
|
||||||
|
"""
|
||||||
|
|
||||||
print '------ Account Collection -------'
|
print '------ Account Collection -------'
|
||||||
self.print_pagination_info(accounts_list)
|
print_pagination_info(accounts_response)
|
||||||
|
print
|
||||||
|
|
||||||
|
for account in accounts_response.get('items', []):
|
||||||
|
print 'Account ID = %s' % account.get('id')
|
||||||
|
print 'Kind = %s' % account.get('kind')
|
||||||
|
print 'Self Link = %s' % account.get('selfLink')
|
||||||
|
print 'Account Name = %s' % account.get('name')
|
||||||
|
print 'Created = %s' % account.get('created')
|
||||||
|
print 'Updated = %s' % account.get('updated')
|
||||||
|
|
||||||
|
child_link = account.get('childLink')
|
||||||
|
print 'Child link href = %s' % child_link.get('href')
|
||||||
|
print 'Child link type = %s' % child_link.get('type')
|
||||||
|
print
|
||||||
|
else:
|
||||||
|
print 'No accounts found.\n'
|
||||||
|
|
||||||
|
|
||||||
|
def print_webproperties(webproperties_response):
|
||||||
|
"""Prints all the web property info in the WebProperties collection.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
webproperties_response: The response object returned from querying the
|
||||||
|
Webproperties collection.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print '------ Web Properties Collection -------'
|
||||||
|
print_pagination_info(webproperties_response)
|
||||||
|
print
|
||||||
|
|
||||||
|
for webproperty in webproperties_response.get('items', []):
|
||||||
|
print 'Kind = %s' % webproperty.get('kind')
|
||||||
|
print 'Account ID = %s' % webproperty.get('accountId')
|
||||||
|
print 'Web Property ID = %s' % webproperty.get('id')
|
||||||
|
print ('Internal Web Property ID = %s' %
|
||||||
|
webproperty.get('internalWebPropertyId'))
|
||||||
|
|
||||||
|
print 'Website URL = %s' % webproperty.get('websiteUrl')
|
||||||
|
print 'Created = %s' % webproperty.get('created')
|
||||||
|
print 'Updated = %s' % webproperty.get('updated')
|
||||||
|
|
||||||
|
print 'Self Link = %s' % webproperty.get('selfLink')
|
||||||
|
parent_link = webproperty.get('parentLink')
|
||||||
|
print 'Parent link href = %s' % parent_link.get('href')
|
||||||
|
print 'Parent link type = %s' % parent_link.get('type')
|
||||||
|
child_link = webproperty.get('childLink')
|
||||||
|
print 'Child link href = %s' % child_link.get('href')
|
||||||
|
print 'Child link type = %s' % child_link.get('type')
|
||||||
|
print
|
||||||
|
else:
|
||||||
|
print 'No webproperties found.\n'
|
||||||
|
|
||||||
|
|
||||||
|
def print_profiles(profiles_response):
|
||||||
|
"""Prints all the profile info in the Profiles Collection.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
profiles_response: The response object returned from querying the
|
||||||
|
Profiles collection.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print '------ Profiles Collection -------'
|
||||||
|
print_pagination_info(profiles_response)
|
||||||
|
print
|
||||||
|
|
||||||
|
for profile in profiles_response.get('items', []):
|
||||||
|
print 'Kind = %s' % profile.get('kind')
|
||||||
|
print 'Account ID = %s' % profile.get('accountId')
|
||||||
|
print 'Web Property ID = %s' % profile.get('webPropertyId')
|
||||||
|
print ('Internal Web Property ID = %s' %
|
||||||
|
profile.get('internalWebPropertyId'))
|
||||||
|
print 'Profile ID = %s' % profile.get('id')
|
||||||
|
print 'Profile Name = %s' % profile.get('name')
|
||||||
|
|
||||||
|
print 'Currency = %s' % profile.get('currency')
|
||||||
|
print 'Timezone = %s' % profile.get('timezone')
|
||||||
|
print 'Default Page = %s' % profile.get('defaultPage')
|
||||||
|
|
||||||
|
print ('Exclude Query Parameters = %s' %
|
||||||
|
profile.get('excludeQueryParameters'))
|
||||||
|
print ('Site Search Category Parameters = %s' %
|
||||||
|
profile.get('siteSearchCategoryParameters'))
|
||||||
|
print ('Site Search Query Parameters = %s' %
|
||||||
|
profile.get('siteSearchQueryParameters'))
|
||||||
|
|
||||||
|
print 'Created = %s' % profile.get('created')
|
||||||
|
print 'Updated = %s' % profile.get('updated')
|
||||||
|
|
||||||
|
print 'Self Link = %s' % profile.get('selfLink')
|
||||||
|
parent_link = profile.get('parentLink')
|
||||||
|
print 'Parent link href = %s' % parent_link.get('href')
|
||||||
|
print 'Parent link type = %s' % parent_link.get('type')
|
||||||
|
child_link = profile.get('childLink')
|
||||||
|
print 'Child link href = %s' % child_link.get('href')
|
||||||
|
print 'Child link type = %s' % child_link.get('type')
|
||||||
|
print
|
||||||
|
else:
|
||||||
|
print 'No profiles found.\n'
|
||||||
|
|
||||||
|
|
||||||
|
def print_goals(goals_response):
|
||||||
|
"""Prints all the goal info in the Goals collection.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
goals_response: The response object returned from querying the Goals
|
||||||
|
collection
|
||||||
|
"""
|
||||||
|
|
||||||
|
print '------ Goals Collection -------'
|
||||||
|
print_pagination_info(goals_response)
|
||||||
|
print
|
||||||
|
|
||||||
|
for goal in goals_response.get('items', []):
|
||||||
|
print 'Goal ID = %s' % goal.get('id')
|
||||||
|
print 'Kind = %s' % goal.get('kind')
|
||||||
|
print 'Self Link = %s' % goal.get('selfLink')
|
||||||
|
|
||||||
|
print 'Account ID = %s' % goal.get('accountId')
|
||||||
|
print 'Web Property ID = %s' % goal.get('webPropertyId')
|
||||||
|
print ('Internal Web Property ID = %s' %
|
||||||
|
goal.get('internalWebPropertyId'))
|
||||||
|
print 'Profile ID = %s' % goal.get('profileId')
|
||||||
|
|
||||||
|
print 'Goal Name = %s' % goal.get('name')
|
||||||
|
print 'Goal Value = %s' % goal.get('value')
|
||||||
|
print 'Goal Active = %s' % goal.get('active')
|
||||||
|
print 'Goal Type = %s' % goal.get('type')
|
||||||
|
|
||||||
|
print 'Created = %s' % goal.get('created')
|
||||||
|
print 'Updated = %s' % goal.get('updated')
|
||||||
|
|
||||||
|
parent_link = goal.get('parentLink')
|
||||||
|
print 'Parent link href = %s' % parent_link.get('href')
|
||||||
|
print 'Parent link type = %s' % parent_link.get('type')
|
||||||
|
|
||||||
|
# Print the goal details depending on the type of goal.
|
||||||
|
if goal.get('urlDestinationDetails'):
|
||||||
|
print_url_destination_goal_details(
|
||||||
|
goal.get('urlDestinationDetails'))
|
||||||
|
|
||||||
|
elif goal.get('visitTimeOnSiteDetails'):
|
||||||
|
print_visit_time_on_site_goal_details(
|
||||||
|
goal.get('visitTimeOnSiteDetails'))
|
||||||
|
|
||||||
|
elif goal.get('visitNumPagesDetails'):
|
||||||
|
print_visit_num_pages_goal_details(
|
||||||
|
goal.get('visitNumPagesDetails'))
|
||||||
|
|
||||||
|
elif goal.get('eventDetails'):
|
||||||
|
print_event_goal_details(goal.get('eventDetails'))
|
||||||
|
|
||||||
|
print
|
||||||
|
else:
|
||||||
|
print 'No goals found.\n'
|
||||||
|
|
||||||
|
|
||||||
|
def print_url_destination_goal_details(goal_details):
|
||||||
|
"""Prints all the URL Destination goal type info.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
goal_details: The details portion of the goal response.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print '------ Url Destination Goal -------'
|
||||||
|
print 'Goal URL = %s' % goal_details.get('url')
|
||||||
|
print 'Case Sensitive = %s' % goal_details.get('caseSensitive')
|
||||||
|
print 'Match Type = %s' % goal_details.get('matchType')
|
||||||
|
print 'First Step Required = %s' % goal_details.get('firstStepRequired')
|
||||||
|
|
||||||
|
print '------ Url Destination Goal Steps -------'
|
||||||
|
for goal_step in goal_details.get('steps', []):
|
||||||
|
print 'Step Number = %s' % goal_step.get('number')
|
||||||
|
print 'Step Name = %s' % goal_step.get('name')
|
||||||
|
print 'Step URL = %s' % goal_step.get('url')
|
||||||
|
else:
|
||||||
|
print 'No Steps Configured'
|
||||||
|
|
||||||
|
|
||||||
|
def print_visit_time_on_site_goal_details(goal_details):
|
||||||
|
"""Prints all the Visit Time On Site goal type info.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
goal_details: The details portion of the goal response.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print '------ Visit Time On Site Goal -------'
|
||||||
|
print 'Comparison Type = %s' % goal_details.get('comparisonType')
|
||||||
|
print 'comparison Value = %s' % goal_details.get('comparisonValue')
|
||||||
|
|
||||||
|
|
||||||
|
def print_visit_num_pages_goal_details(goal_details):
|
||||||
|
"""Prints all the Visit Num Pages goal type info.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
goal_details: The details portion of the goal response.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print '------ Visit Num Pages Goal -------'
|
||||||
|
print 'Comparison Type = %s' % goal_details.get('comparisonType')
|
||||||
|
print 'comparison Value = %s' % goal_details.get('comparisonValue')
|
||||||
|
|
||||||
|
|
||||||
|
def print_event_goal_details(goal_details):
|
||||||
|
"""Prints all the Event goal type info.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
goal_details: The details portion of the goal response.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print '------ Event Goal -------'
|
||||||
|
print 'Use Event Value = %s' % goal_details.get('useEventValue')
|
||||||
|
|
||||||
|
for event_condition in goal_details.get('eventConditions', []):
|
||||||
|
event_type = event_condition.get('type')
|
||||||
|
print 'Type = %s' % event_type
|
||||||
|
|
||||||
|
if event_type in ('CATEGORY', 'ACTION', 'LABEL'):
|
||||||
|
print 'Match Type = %s' % event_condition.get('matchType')
|
||||||
|
print 'Expression = %s' % event_condition.get('expression')
|
||||||
|
else: # VALUE type.
|
||||||
|
print 'Comparison Type = %s' % event_condition.get('comparisonType')
|
||||||
|
print 'Comparison Value = %s' % event_condition.get('comparisonValue')
|
||||||
|
|
||||||
|
|
||||||
|
def print_segments(segments_response):
|
||||||
|
"""Prints all the segment info in the Segments collection.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
segments_response: The response object returned from querying the
|
||||||
|
Segments collection.
|
||||||
|
"""
|
||||||
|
|
||||||
|
print '------ Segments Collection -------'
|
||||||
|
print_pagination_info(segments_response)
|
||||||
|
print
|
||||||
|
|
||||||
|
for segment in segments_response.get('items', []):
|
||||||
|
print 'Segment ID = %s' % segment.get('id')
|
||||||
|
print 'Kind = %s' % segment.get('kind')
|
||||||
|
print 'Self Link = %s' % segment.get('selfLink')
|
||||||
|
print 'Name = %s' % segment.get('name')
|
||||||
|
print 'Definition = %s' % segment.get('definition')
|
||||||
|
print 'Created = %s' % segment.get('created')
|
||||||
|
print 'Updated = %s' % segment.get('updated')
|
||||||
print
|
print
|
||||||
|
|
||||||
for account in accounts_list.get('items'):
|
|
||||||
print 'Account ID = %s' % account.get('id')
|
|
||||||
print 'Kind = %s' % account.get('kind')
|
|
||||||
print 'Self Link = %s' % account.get('selfLink')
|
|
||||||
print 'Account Name = %s' % account.get('name')
|
|
||||||
print 'Created = %s' % account.get('created')
|
|
||||||
print 'Updated = %s' % account.get('updated')
|
|
||||||
|
|
||||||
child_link = account.get('childLink')
|
def print_pagination_info(management_response):
|
||||||
print 'Child link href = %s' % child_link.get('href')
|
"""Prints common pagination details.
|
||||||
print 'Child link type = %s' % child_link.get('type')
|
|
||||||
print
|
|
||||||
|
|
||||||
def print_webproperties(self, webproperties_list):
|
Args:
|
||||||
"""Prints all the web property info in the WebProperties Collection."""
|
management_response: The common reponse object for each collection in the
|
||||||
|
Management API.
|
||||||
|
"""
|
||||||
|
|
||||||
print '------ Web Properties Collection -------'
|
print 'Items per page = %s' % management_response.get('itemsPerPage')
|
||||||
self.print_pagination_info(webproperties_list)
|
print 'Total Results = %s' % management_response.get('totalResults')
|
||||||
print
|
print 'Start Index = %s' % management_response.get('startIndex')
|
||||||
|
|
||||||
for webproperty in webproperties_list.get('items'):
|
# These only have values if other result pages exist.
|
||||||
print 'Kind = %s' % webproperty.get('kind')
|
if management_response.get('previousLink'):
|
||||||
print 'Account ID = %s' % webproperty.get('accountId')
|
print 'Previous Link = %s' % management_response.get('previousLink')
|
||||||
print 'Web Property ID = %s' % webproperty.get('id')
|
if management_response.get('nextLink'):
|
||||||
print ('Internal Web Property ID = %s' %
|
print 'Next Link = %s' % management_response.get('nextLink')
|
||||||
webproperty.get('internalWebPropertyId'))
|
|
||||||
|
|
||||||
print 'Website URL = %s' % webproperty.get('websiteUrl')
|
|
||||||
print 'Created = %s' % webproperty.get('created')
|
|
||||||
print 'Updated = %s' % webproperty.get('updated')
|
|
||||||
|
|
||||||
print 'Self Link = %s' % webproperty.get('selfLink')
|
|
||||||
parent_link = webproperty.get('parentLink')
|
|
||||||
print 'Parent link href = %s' % parent_link.get('href')
|
|
||||||
print 'Parent link type = %s' % parent_link.get('type')
|
|
||||||
child_link = webproperty.get('childLink')
|
|
||||||
print 'Child link href = %s' % child_link.get('href')
|
|
||||||
print 'Child link type = %s' % child_link.get('type')
|
|
||||||
print
|
|
||||||
|
|
||||||
def print_profiles(self, profiles_list):
|
|
||||||
"""Prints all the profile info in the Profiles Collection."""
|
|
||||||
|
|
||||||
print '------ Profiles Collection -------'
|
|
||||||
self.print_pagination_info(profiles_list)
|
|
||||||
print
|
|
||||||
|
|
||||||
for profile in profiles_list.get('items'):
|
|
||||||
print 'Kind = %s' % profile.get('kind')
|
|
||||||
print 'Account ID = %s' % profile.get('accountId')
|
|
||||||
print 'Web Property ID = %s' % profile.get('webPropertyId')
|
|
||||||
print ('Internal Web Property ID = %s' %
|
|
||||||
profile.get('internalWebPropertyId'))
|
|
||||||
print 'Profile ID = %s' % profile.get('id')
|
|
||||||
print 'Profile Name = %s' % profile.get('name')
|
|
||||||
|
|
||||||
print 'Currency = %s' % profile.get('currency')
|
|
||||||
print 'Timezone = %s' % profile.get('timezone')
|
|
||||||
print 'Default Page = %s' % profile.get('defaultPage')
|
|
||||||
|
|
||||||
print ('Exclude Query Parameters = %s' %
|
|
||||||
profile.get('excludeQueryParameters'))
|
|
||||||
print ('Site Search Category Parameters = %s' %
|
|
||||||
profile.get('siteSearchCategoryParameters'))
|
|
||||||
print ('Site Search Query Parameters = %s' %
|
|
||||||
profile.get('siteSearchQueryParameters'))
|
|
||||||
|
|
||||||
print 'Created = %s' % profile.get('created')
|
|
||||||
print 'Updated = %s' % profile.get('updated')
|
|
||||||
|
|
||||||
print 'Self Link = %s' % profile.get('selfLink')
|
|
||||||
parent_link = profile.get('parentLink')
|
|
||||||
print 'Parent link href = %s' % parent_link.get('href')
|
|
||||||
print 'Parent link type = %s' % parent_link.get('type')
|
|
||||||
child_link = profile.get('childLink')
|
|
||||||
print 'Child link href = %s' % child_link.get('href')
|
|
||||||
print 'Child link type = %s' % child_link.get('type')
|
|
||||||
print
|
|
||||||
|
|
||||||
def print_goals(self, goals_list):
|
|
||||||
"""Prints all the goal info in the Goals Collection."""
|
|
||||||
|
|
||||||
print '------ Goals Collection -------'
|
|
||||||
self.print_pagination_info(goals_list)
|
|
||||||
print
|
|
||||||
|
|
||||||
for goal in goals_list.get('items'):
|
|
||||||
print 'Goal ID = %s' % goal.get('id')
|
|
||||||
print 'Kind = %s' % goal.get('kind')
|
|
||||||
print 'Self Link = %s' % goal.get('selfLink')
|
|
||||||
|
|
||||||
print 'Account ID = %s' % goal.get('accountId')
|
|
||||||
print 'Web Property ID = %s' % goal.get('webPropertyId')
|
|
||||||
print ('Internal Web Property ID = %s' %
|
|
||||||
goal.get('internalWebPropertyId'))
|
|
||||||
print 'Profile ID = %s' % goal.get('profileId')
|
|
||||||
|
|
||||||
print 'Goal Name = %s' % goal.get('name')
|
|
||||||
print 'Goal Value = %s' % goal.get('value')
|
|
||||||
print 'Goal Active = %s' % goal.get('active')
|
|
||||||
print 'Goal Type = %s' % goal.get('type')
|
|
||||||
|
|
||||||
print 'Created = %s' % goal.get('created')
|
|
||||||
print 'Updated = %s' % goal.get('updated')
|
|
||||||
|
|
||||||
parent_link = goal.get('parentLink')
|
|
||||||
print 'Parent link href = %s' % parent_link.get('href')
|
|
||||||
print 'Parent link type = %s' % parent_link.get('type')
|
|
||||||
|
|
||||||
# Print the goal details depending on the type of goal.
|
|
||||||
if goal.get('urlDestinationDetails'):
|
|
||||||
self.print_url_destination_goal_details(
|
|
||||||
goal.get('urlDestinationDetails'))
|
|
||||||
|
|
||||||
elif goal.get('visitTimeOnSiteDetails'):
|
|
||||||
self.print_visit_time_on_site_goal_details(
|
|
||||||
goal.get('visitTimeOnSiteDetails'))
|
|
||||||
|
|
||||||
elif goal.get('visitNumPagesDetails'):
|
|
||||||
self.print_visit_num_pages_goal_details(
|
|
||||||
goal.get('visitNumPagesDetails'))
|
|
||||||
|
|
||||||
elif goal.get('eventDetails'):
|
|
||||||
self.print_event_goal_details(goal.get('eventDetails'))
|
|
||||||
|
|
||||||
print
|
|
||||||
|
|
||||||
def print_url_destination_goal_details(self, goal_details):
|
|
||||||
"""Prints all the URL Destination goal type info."""
|
|
||||||
|
|
||||||
print '------ Url Destination Goal -------'
|
|
||||||
print 'Goal URL = %s' % goal_details.get('url')
|
|
||||||
print 'Case Sensitive = %s' % goal_details.get('caseSensitive')
|
|
||||||
print 'Match Type = %s' % goal_details.get('matchType')
|
|
||||||
print 'First Step Required = %s' % goal_details.get('firstStepRequired')
|
|
||||||
|
|
||||||
print '------ Url Destination Goal Steps -------'
|
|
||||||
if goal_details.get('steps'):
|
|
||||||
for goal_step in goal_details.get('steps'):
|
|
||||||
print 'Step Number = %s' % goal_step.get('number')
|
|
||||||
print 'Step Name = %s' % goal_step.get('name')
|
|
||||||
print 'Step URL = %s' % goal_step.get('url')
|
|
||||||
else:
|
|
||||||
print 'No Steps Configured'
|
|
||||||
|
|
||||||
def print_visit_time_on_site_goal_details(self, goal_details):
|
|
||||||
"""Prints all the Visit Time On Site goal type info."""
|
|
||||||
|
|
||||||
print '------ Visit Time On Site Goal -------'
|
|
||||||
print 'Comparison Type = %s' % goal_details.get('comparisonType')
|
|
||||||
print 'comparison Value = %s' % goal_details.get('comparisonValue')
|
|
||||||
|
|
||||||
def print_visit_num_pages_goal_details(self, goal_details):
|
|
||||||
"""Prints all the Visit Num Pages goal type info."""
|
|
||||||
|
|
||||||
print '------ Visit Num Pages Goal -------'
|
|
||||||
print 'Comparison Type = %s' % goal_details.get('comparisonType')
|
|
||||||
print 'comparison Value = %s' % goal_details.get('comparisonValue')
|
|
||||||
|
|
||||||
def print_event_goal_details(self, goal_details):
|
|
||||||
"""Prints all the Event goal type info."""
|
|
||||||
|
|
||||||
print '------ Event Goal -------'
|
|
||||||
print 'Use Event Value = %s' % goal_details.get('useEventValue')
|
|
||||||
|
|
||||||
for event_condition in goal_details.get('eventConditions'):
|
|
||||||
event_type = event_condition.get('type')
|
|
||||||
print 'Type = %s' % event_type
|
|
||||||
|
|
||||||
if event_type in ('CATEGORY', 'ACTION', 'LABEL'):
|
|
||||||
print 'Match Type = %s' % event_condition.get('matchType')
|
|
||||||
print 'Expression = %s' % event_condition.get('expression')
|
|
||||||
else: # VALUE type.
|
|
||||||
print 'Comparison Type = %s' % event_condition.get('comparisonType')
|
|
||||||
print 'Comparison Value = %s' % event_condition.get('comparisonValue')
|
|
||||||
|
|
||||||
def print_segments(self, segments_list):
|
|
||||||
"""Prints all the segment info in the Segments Collection."""
|
|
||||||
|
|
||||||
print '------ Segments Collection -------'
|
|
||||||
self.print_pagination_info(segments_list)
|
|
||||||
print
|
|
||||||
|
|
||||||
for segment in segments_list.get('items'):
|
|
||||||
print 'Segment ID = %s' % segment.get('id')
|
|
||||||
print 'Kind = %s' % segment.get('kind')
|
|
||||||
print 'Self Link = %s' % segment.get('selfLink')
|
|
||||||
print 'Name = %s' % segment.get('name')
|
|
||||||
print 'Definition = %s' % segment.get('definition')
|
|
||||||
print 'Created = %s' % segment.get('created')
|
|
||||||
print 'Updated = %s' % segment.get('updated')
|
|
||||||
print
|
|
||||||
|
|
||||||
def print_pagination_info(self, mgmt_list):
|
|
||||||
"""Prints common pagination details."""
|
|
||||||
|
|
||||||
print 'Items per page = %s' % mgmt_list.get('itemsPerPage')
|
|
||||||
print 'Total Results = %s' % mgmt_list.get('totalResults')
|
|
||||||
print 'Start Index = %s' % mgmt_list.get('startIndex')
|
|
||||||
|
|
||||||
# These only have values if other result pages exist.
|
|
||||||
if mgmt_list.get('previousLink'):
|
|
||||||
print 'Previous Link = %s' % mgmt_list.get('previousLink')
|
|
||||||
if mgmt_list.get('nextLink'):
|
|
||||||
print 'Next Link = %s' % mgmt_list.get('nextLink')
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
131
samples/analytics/sample_utils.py
Normal file
131
samples/analytics/sample_utils.py
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
#
|
||||||
|
# Copyright 2012 Google Inc. All Rights Reserved.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
"""Utilities for Analytics API code samples.
|
||||||
|
|
||||||
|
Handles various tasks to do with logging, authentication and initialization.
|
||||||
|
Mostly taken from Sergio :)
|
||||||
|
|
||||||
|
Before You Begin:
|
||||||
|
|
||||||
|
You must update the client_secrets.json file with a client id, client secret,
|
||||||
|
and the redirect uri. You get these values by creating a new project
|
||||||
|
in the Google APIs console and registering for OAuth2.0 for installed
|
||||||
|
applications: https://code.google.com/apis/console
|
||||||
|
|
||||||
|
Also all OAuth2.0 tokens are stored for resue in the file specified
|
||||||
|
as TOKEN_FILE_NAME. You can modify this file name if you wish.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__author__ = ('sergio.gomes@google.com (Sergio Gomes)'
|
||||||
|
'api.nickm@gmail.com (Nick Mihailovski)')
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from apiclient.discovery import build
|
||||||
|
import gflags
|
||||||
|
import httplib2
|
||||||
|
from oauth2client.client import flow_from_clientsecrets
|
||||||
|
from oauth2client.file import Storage
|
||||||
|
from oauth2client.tools import run
|
||||||
|
|
||||||
|
|
||||||
|
FLAGS = gflags.FLAGS
|
||||||
|
|
||||||
|
# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
|
||||||
|
# application, including client_id and client_secret. You get these values by
|
||||||
|
# creating a new project in the Google APIs console and registering for
|
||||||
|
# OAuth2.0 for installed applications: <https://code.google.com/apis/console>
|
||||||
|
CLIENT_SECRETS = 'client_secrets.json'
|
||||||
|
|
||||||
|
|
||||||
|
# Helpful message to display in the browser if the CLIENT_SECRETS file
|
||||||
|
# is missing.
|
||||||
|
MISSING_CLIENT_SECRETS_MESSAGE = """
|
||||||
|
WARNING: Please configure OAuth 2.0
|
||||||
|
|
||||||
|
To make this sample run you will need to populate the client_secrets.json file
|
||||||
|
found at:
|
||||||
|
|
||||||
|
%s
|
||||||
|
|
||||||
|
with information from the APIs Console <https://code.google.com/apis/console>.
|
||||||
|
|
||||||
|
""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
|
||||||
|
|
||||||
|
# Set up a Flow object to be used if we need to authenticate.
|
||||||
|
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
|
||||||
|
scope='https://www.googleapis.com/auth/analytics.readonly',
|
||||||
|
message=MISSING_CLIENT_SECRETS_MESSAGE)
|
||||||
|
|
||||||
|
# The gflags module makes defining command-line options easy for applications.
|
||||||
|
# Run this program with the '--help' argument to see all the flags that it
|
||||||
|
# understands.
|
||||||
|
gflags.DEFINE_enum('logging_level', 'ERROR',
|
||||||
|
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
|
||||||
|
'Set the level of logging detail.')
|
||||||
|
|
||||||
|
|
||||||
|
# Name of file that will store the access and refresh tokens to access
|
||||||
|
# the API without having to login each time. Make sure this file is in
|
||||||
|
# a secure place.
|
||||||
|
TOKEN_FILE_NAME = 'analytics.dat'
|
||||||
|
|
||||||
|
|
||||||
|
def process_flags(argv):
|
||||||
|
"""Uses the command-line flags to set the logging level.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
argv: List of command line arguments passed to the python script.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Let the gflags module process the command-line arguments.
|
||||||
|
try:
|
||||||
|
argv = FLAGS(argv)
|
||||||
|
except gflags.FlagsError, e:
|
||||||
|
print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Set the logging according to the command-line flag.
|
||||||
|
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
|
||||||
|
|
||||||
|
|
||||||
|
def initialize_service():
|
||||||
|
"""Returns an instance of service from discovery data and does auth.
|
||||||
|
|
||||||
|
This method tries to read any existing OAuth 2.0 credentials from the
|
||||||
|
Storage object. If the credentials do not exist, new credentials are
|
||||||
|
obtained. The crdentials are used to authorize an http object. The
|
||||||
|
http object is used to build the analytics service object.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
An analytics v3 service object.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Create an httplib2.Http object to handle our HTTP requests.
|
||||||
|
http = httplib2.Http()
|
||||||
|
|
||||||
|
# Prepare credentials, and authorize HTTP object with them.
|
||||||
|
storage = Storage(TOKEN_FILE_NAME)
|
||||||
|
credentials = storage.get()
|
||||||
|
if credentials is None or credentials.invalid:
|
||||||
|
credentials = run(FLOW, storage)
|
||||||
|
|
||||||
|
http = credentials.authorize(http)
|
||||||
|
|
||||||
|
# Retrieve service.
|
||||||
|
return build('analytics', 'v3', http=http)
|
||||||
Reference in New Issue
Block a user