Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import argparse
- import sys
- import csv
- import string
- import ssl
- from apiclient.errors import HttpError
- from apiclient import sample_tools
- from oauth2client.client import AccessTokenRefreshError
- from datetime import timedelta, date, datetime
- class SampledDataError(Exception): pass
- def main(argv, request_list):
- # Authenticate and construct service.
- service, flags = sample_tools.init(
- argv, 'analytics', 'v3', __doc__, __file__,
- scope='https://www.googleapis.com/auth/analytics.readonly')
- # Try to make a request to the API. Print the results or handle errors.
- try:
- profile_id = profile_ids[profile]
- if not profile_id:
- print 'Could not find a valid profile for this user.'
- else:
- for start_date, end_date in date_ranges:
- # limit = ga_query(service, profile_id, 0,
- # start_date, end_date).get('totalResults')
- # for pag_index in xrange(0, limit, 10000):
- for i in range(len(request_list)):
- results = ga_query(service, profile_id,
- start_date, end_date, request_list[i]['segment'])
- print_results(results, start_date, end_date, request_list[i]['name'],i)
- 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')
- except SampledDataError:
- # force an error if ever a query returns data that is sampled!
- print ('Error: Query contains sampled data!')
- except ssl.SSLError, error:
- print error
- def ga_query(service, profile_id, start_date, end_date, ga_segment):
- print ga_segment
- return service.data().ga().get(
- ids='ga:' + profile_id,
- start_date=start_date,
- end_date=end_date,
- metrics='ga:sessions',
- dimensions='ga:date,ga:hostname,ga:deviceCategory',
- segment=ga_segment,
- filters='ga:hostname=~^www.(aeg.(be|co.uk|com.es|de|nl)|electrolux.(ch|fr|it|pl|ru|se))$',
- samplingLevel='HIGHER_PRECISION').execute()
- def print_results(results, start_date, end_date, request_name,i):
- """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.
- """
- # New write header
- # if i == 0:
- # if (start_date, end_date) == date_ranges[0]:
- # print 'Profile Name: %s' % results.get('profileInfo').get('profileName')
- # columnHeaders = results.get('columnHeaders')
- # cleanHeaders = []
- #
- # cleanHeaders = [str(h['name']) for h in columnHeaders]
- # cleanHeaders.append('Metric')
- #
- # writer.writerow(cleanHeaders)
- print 'Now pulling data from %s to %s.' %(start_date, end_date)
- current_date = datetime.strptime(start_date, "%Y-%m-%d").strftime("%d/%m/%Y")
- # Print data table.
- if results.get('rows', []):
- print results.get('rows')
- for row in results.get('rows'):
- row.append(request_name)
- for i in range(len(row)):
- old, new = row[i], str()
- for s in old:
- new += s if s in string.printable else ''
- row[i] = new
- row.append(str(current_date))
- writer.writerow(row)
- else:
- print 'No Rows Found'
- limit = results.get('totalResults')
- return None
- ##profile_ids = profile_ids = {'My Profile 1': '1234567',
- #'My Profile 2': '1234568',
- #'My Profile 3': '1234569',
- #'My Profile 4': '1234561'}
- # Uncomment this line & replace with 'profile name': 'id' to query a single profile
- # Delete or comment out this line to loop over multiple profiles.
- profile_ids = {'T1_All_Sites': '180255716'}#{'ELUX Sweden': '136792100','ELUX Italy': '136785306','ELUX Russia': '136854754','ELUX Poland': '136756525','ELUX France': '136781829','ELUX Switzerland': '136846376','AEG UK':'136678083','AEG Belgium': '136774720','AEG Netherlands': '136778122','AEG Germany': '136784414','AEG Spain': '136756133'}
- #{'T1_All_Sites': '180255716'}{'Fake Rollup Core Goals': '148389067'}
- def daterange(start_date, end_date):
- for n in range(int ((end_date - start_date).days)):
- yield start_date + timedelta(n)
- dates_list = []
- start_date = date(2018, 10, 24)
- end_date = date(2019, 6, 17)
- for single_date in daterange(start_date, end_date):
- add_date = single_date.strftime("%Y-%m-%d")
- datetuple = (add_date, add_date)
- dates_list.append(datetuple)
- print dates_list
- date_ranges = dates_list ##,
- # ('2015-10-01',
- # '2015-10-31'),
- # ('2015-11-01',
- # '2015-11-30',
- # ('2015-12-01',
- # '2015-12-31')]
- request_list = [{"name":"start_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/)|(/productregistration/start)"},
- {"name":"complete_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/confirmation)|(/productregistration/personal_details)"},
- {"name":"product-search_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/(.*)search)"},
- {"name":"product-details_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/(.*)details)"},
- {"name":"incentive_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/(.*)incentive)"},
- {"name":"loginSuccess_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/)|(/productregistration/start);ga:pagePath=~/mypages(.*)loginStatus=True"},
- {"name":"createAccountSuccess_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/)|(/productregistration/start);ga:pagePath=~/mypages(.*)createStatus=True"},
- {"name":"prod-search-start_Yesterday","segment":"sessions::condition::ga:eventAction=~click(.*)product(.*)box"},
- {"name":"prod-search-btn_Yesterday","segment":"sessions::condition::ga:eventAction==ProductSearchBtn"},
- {"name":"complete+incentive_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/confirmation)|(/productregistration/personal_details);ga:pagePath=~(/mypages/(product-registration|register-a-product)/(.*)incentive)"},
- {"name":"product-details+incentive_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/(product-registration|register-a-product)/(.*)details);ga:pagePath=~(/mypages/(product-registration|register-a-product)/(.*)incentive)"},
- {"name":"loginStart_Yesterday","segment":"sessions::condition::ga:pagePath=~(/mypages/login/default)|((/mypages/(product-registration|register-a-product))(.*)/(login-attempt|auth))"},
- {"name":"createAccountStart_Yesterday","segment":"sessions::condition::ga:pagePath=~modal-create-account(.*)open"},
- {"name":"PS-search_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/search(.*)searchtype(.*)photo"},
- {"name":"PS-incentive_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/incentive(.*)searchtype(.*)photo"},
- {"name":"PS-auth_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/auth(.*)searchtype(.*)photo"},
- {"name":"PS-product-details_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/details(.*)searchtype(.*)photo"},
- {"name":"PS-complete_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/confirmation(.*)searchtype(.*)photo"},
- {"name":"MS-search_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/search(.*)searchtype(.*)input"},
- {"name":"MS-incentive_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/incentive(.*)searchtype(.*)input"},
- {"name":"MS-auth_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/auth(.*)searchtype(.*)input"},
- {"name":"MS-product-details_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/details(.*)searchtype(.*)input"},
- {"name":"MS-complete_Yesterday","segment":"sessions::condition::ga:pagePath=~/mypages/(product-registration|register-a-product)/confirmation(.*)searchtype(.*)input"},
- {"name":"MS-FoundSearches_Yesterday","segment":"sessions::condition::ga:pagePath=~(.*)searchtype(.*)input;ga:eventcategory==ProductRegistration;ga:eventaction==ProductSearchResults"},
- {"name":"MS-NotFoundSearches_Yesterday","segment":"sessions::condition::ga:pagePath=~(.*)searchtype(.*)input;ga:eventcategory==ProductRegistration;ga:eventaction==ProductSearchResults"},
- {"name":"PS-FoundSearches_Yesterday","segment":"sessions::condition::ga:pagePath=~(.*)searchtype(.*)photo;ga:eventcategory==ProductRegistration;ga:eventaction==ProductSearchResults"},
- {"name":"PS-NotFoundSearches_Yesterday","segment":"sessions::condition::ga:pagePath=~(.*)searchtype(.*)photo;ga:eventcategory==ProductRegistration;ga:eventaction==ProductSearchResults"},
- {"name":"PS-BtnClick_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Click:PhotosearchUploadBtn"},
- {"name":"MS-BoxClick_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Click:ProductSearchBox"},
- {"name":"PS-PNCFound_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==PhotoSearch;ga:eventlabel==PNCFound"},
- #{"name":"PS-PNCNotFound_Yesterday","segment":""},
- #{"name":"PS-ConfirmImage_Yesterday","segment":""},
- {"name":"PS-IncentiveAccept_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Incentives;ga:eventLabel==Click:YESBtn;ga:pagePath=~incentive(.*)searchtype(.*)photo"},
- {"name":"PS-IncentiveDecline_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Incentives;ga:eventLabel==Click:NOBtn;ga:pagePath=~incentive(.*)searchtype(.*)photo"},
- {"name":"MS-IncentiveAccept_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Incentives;ga:eventLabel==Click:YESBtn;ga:pagePath=~incentive(.*)searchtype(.*)input"},
- {"name":"MS-IncentiveDecline_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Incentives;ga:eventLabel==Click:NOBtn;ga:pagePath=~incentive(.*)searchtype(.*)input"},
- {"name":"PS-UploadReceipt_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Click:UploadReceiptBtn;ga:pagePath=~details(.*)searchtype(.*)photo"},
- {"name":"MS-UploadReceipt_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Click:UploadReceiptBtn;ga:pagePath=~details(.*)searchtype(.*)input"},
- {"name":"SubmissionError_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Info:SubmissionError"},
- {"name":"Initial-Interaction-Any_Yesterday","segment":"sessions::condition::ga:eventcategory==ProductRegistration;ga:eventaction==Click:PhotosearchUploadBtn,ga:eventaction==Click:ProductSearchBox"}]
- for profile in sorted(profile_ids):
- path = './' #replace with path to your folder where csv file with data will be written
- filename = 'post_purchase_prod_reg_june18.csv' #replace with your filename. Note %s is a placeholder variable and the profile name you specified on row 162 will be written here
- with open(path + filename, 'at') as f:
- writer = csv.writer(f, lineterminator='\n')
- if __name__ == '__main__': main(sys.argv,request_list)
- print "Profile done. Next profile..."
- print "All profiles done."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement