I'm using Python to extract some data from the Google Analytics Core Reporting API. I've managed to use functions to make different calls to the API (below are just two examples) but I'm wondering how can I refactor this to make it even shorter? There's quite a lot of duplicate code still.
def get_pvs(service, profile_id, start_date, end_date, type, data):
if type == "url":
return service.data().ga().get(
ids = 'ga:' + profile_id,
start_date = start_date,
end_date = end_date,
metrics = 'ga:pageviews',
dimensions = 'ga:pagePath',
filters = 'ga:pageviews!=0',
sort = '-ga:pageviews',
max_results = '10000').execute()
elif type == "author":
return service.data().ga().get(
ids = 'ga:' + profile_id,
start_date = start_date,
end_date = end_date,
metrics = 'ga:pageviews',
# Post Author
dimensions = 'ga:dimension2',
sort = '-ga:pageviews',
max_results = '100').execute()
Create a dictionary with type-specific arguments, then apply that with **kw
:
def get_pvs(service, profile_id, start_date, end_date, type, data):
if type == 'url':
kwargs = {
'dimensions': 'ga:pagePath',
'filters': 'ga:pageviews!=0',
'maxresults': 100
}
elif type == 'author':
kwargs = {
'dimensions': 'ga:dimension2',
'max_results': '100'
}
return service.data().ga().get(
ids = 'ga:' + profile_id,
start_date = start_date,
end_date = end_date,
metrics = 'ga:pageviews',
sort = '-ga:pageviews',
**kwargs).execute()
I left the common arguments in place. if type
can have more values, then you probably need to add a else: return None
too.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments