Advertisement
Guest User

Untitled

a guest
Dec 27th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.70 KB | None | 0 0
  1. """A simple example of how to access the Google Analytics API."""
  2.  
  3. import os
  4. import argparse
  5. from apiclient.discovery import build
  6. from oauth2client.client import SignedJwtAssertionCredentials
  7. import httplib2
  8. from oauth2client import client
  9. from oauth2client import file
  10. from oauth2client import tools
  11. import sys
  12. import json
  13.  
  14. import urllib
  15. import urllib2
  16. sys.path.insert(1, '/Library/Python/2.7/site-packages')
  17. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  18.  
  19.  
  20.  
  21. def get_service(api_name, api_version, scope, key_file_location,
  22.                 service_account_email):
  23.   """Get a service that communicates to a Google API.
  24.  
  25.  Args:
  26.    api_name: The name of the api to connect to.
  27.    api_version: The api version to connect to.
  28.    scope: A list auth scopes to authorize for the application.
  29.    key_file_location: The path to a valid service account p12 key file.
  30.    service_account_email: The service account email address.
  31.  
  32.  Returns:
  33.    A service that is connected to the specified API.
  34.  """
  35.  
  36.   # Load the private key associated with the Google service account
  37.   with open(key_file_location) as json_file:
  38.     json_data = json.load(json_file)
  39.  
  40.   # Get and sign JWT
  41.   credentials = SignedJwtAssertionCredentials(json_data['client_email'], json_data['private_key'], scope)
  42.  
  43.   http = credentials.authorize(httplib2.Http())
  44.  
  45.   # Build the service object.
  46.   service = build(api_name, api_version, http=http)
  47.  
  48.   return service
  49.  
  50.  
  51. def get_first_profile_id(service):
  52.   # Use the Analytics service object to get the first profile id.
  53.  
  54.   # Get a list of all Google Analytics accounts for this user
  55.   accounts = service.management().accounts().list().execute()
  56.  
  57.   if accounts.get('items'):
  58.     # Get the first Google Analytics account.
  59.     account = accounts.get('items')[0].get('id')
  60.  
  61.     # Get a list of all the properties for the first account.
  62.     properties = service.management().webproperties().list(
  63.         accountId=account).execute()
  64.  
  65.     if properties.get('items'):
  66.       # Get the first property id.
  67.       property = properties.get('items')[0].get('id')
  68.  
  69.       # Get a list of all views (profiles) for the first property.
  70.       profiles = service.management().profiles().list(
  71.           accountId=account,
  72.           webPropertyId=property).execute()
  73.  
  74.       if profiles.get('items'):
  75.         # return the first view (profile) id.
  76.         return profiles.get('items')[0].get('id')
  77.  
  78.   return None
  79.  
  80.  
  81. def get_results(service, profile_id):
  82.   # Use the Analytics Service Object to query the Core Reporting API
  83.   # for the number of sessions within the past seven days.
  84.   return service.data().ga().get(
  85.       ids='ga:' + profile_id,
  86.       start_date='7daysAgo',
  87.       end_date='today',
  88.       metrics='ga:sessions'
  89.     ).execute()
  90.  
  91.  
  92. def print_results(results):
  93.   # Print data nicely for the user.
  94.   if results:
  95.     print 'View (Profile): %s' % results.get('profileInfo').get('profileName')
  96.     print 'Total Sessions: %s' % results.get('rows')[0][0]
  97.  
  98.   else:
  99.     print 'No results found'
  100.  
  101.  
  102. def main():
  103.   # Define the auth scopes to request.
  104.   scope = ['https://www.googleapis.com/auth/analytics.readonly']
  105.  
  106.   # Use the developer console and replace the values with your
  107.   # service account email and relative location of your key file.
  108.   service_account_email = '[email protected]'
  109.   key_file_location = os.path.join(BASE_DIR, 'analytics/KEY-40f89e410035.json')
  110.  
  111.   # Authenticate and construct service.
  112.   service = get_service('analytics', 'v3', scope, key_file_location, service_account_email)
  113.   profile = get_first_profile_id(service)
  114.   print_results(get_results(service, profile))
  115.  
  116.  
  117. if __name__ == '__main__':
  118.   main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement