Created
November 15, 2012 21:16
-
-
Save anderser/4081329 to your computer and use it in GitHub Desktop.
Get Google analytics metrics for single url/article
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from local_settings import GOOGLE_USER, GOOGLE_PWD | |
from googleanalytics import Connection | |
from datetime import date | |
#googleanalytics is found here: https://github.com/clintecker/python-googleanalytics/ | |
gaaccounts = { | |
'myaccountname': '1234567', | |
} | |
class TV2GAClient(object): | |
"""Usage: | |
ga = TV2GAClient(GOOGLE_USER, GOOGLE_PWD) | |
start_date = date(2010, 11, 01) | |
end_date = date(2010, 11, 30) | |
print ga.get_metrics_for_article('myaccountname', '3335992', start_date, end_date) | |
""" | |
def __init__(self, guser, gpasswd): | |
self.conn = Connection(guser, gpasswd) | |
self.accounts = {} | |
self.accountname = None | |
#cache accounts to be used | |
self.get_accounts() | |
def get_accounts(self): | |
print "Getting GA accounts...." | |
for k,v in gaaccounts.iteritems(): | |
self.accounts[k] = self.conn.get_account(v) | |
print self.accounts | |
def get_metrics_for_article(self, | |
accountname, | |
articleid, | |
startdate, | |
enddate, | |
metrics=[ | |
'uniquePageviews', | |
'Pageviews', | |
'avgPageLoadTime', | |
'bounces', | |
'exitRate', | |
'entrances', | |
]): | |
""" | |
Gets the metrics for a single url/article based on the articleid beeing in the url | |
If more results are returned (i.e. the articlid is not unique) then only first url | |
is returned and used. Put in a list of the metrics you want to retrieve, defaults provided | |
""" | |
#this defines a filter that searches for all urls containing the articleid, you could | |
#replace this with other regular expressions | |
filters = [['pagePath', '=~', '.*%s.*' % str(articleid)],] | |
try: | |
data = self.accounts[accountname].get_data(startdate, | |
enddate, | |
metrics=metrics, | |
dimensions=['pagePath',], | |
max_results=1, | |
filters=filters, | |
sort=['-%s'% metrics[0],] | |
) | |
except: | |
print "GA:Error: Could not get account data list for accountname %s" % accountname | |
return None | |
else: | |
if len(data) > 0: | |
try: | |
return dict(zip([k.lower() for k in metrics], [str(v) for v in data.list[0][1]])) | |
except: | |
return None | |
print "Exception: No GA-pageviews for %s. Account name: %s. Data list: %s" % str(str(filters), accountname, str(data.list)) | |
else: | |
print "Data list empty: No GA-pageviews for %s. Account name: %s. Data list: %s" % (str(filters), accountname, str(data.list)) | |
return None | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment