我正在使用Python從Google Analytics核心報告API中提取一些數據。我設法使用函數對API進行不同的調用(下面只是兩個示例),但我想知道如何重構這個以使它更短?還有很多重複的代碼。我該如何重構這段代碼才能更簡潔?
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()
我們仍然應該把這件作品放在功能裏面嗎? – kmario23
是的,我已經添加了函數定義行來澄清。 –