如何重构此代码以使其更简洁?

时间:2016-02-09 15:52:37

标签: python python-2.7 google-analytics google-analytics-api

我正在使用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()   

2 个答案:

答案 0 :(得分:7)

使用特定于类型的参数创建字典,然后将其应用于**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()   

我留下了共同的论据。如果type可以包含更多值,那么您可能还需要添加else: return None

答案 1 :(得分:0)

另一种方法:

TYPE_SETTINGS = {
        'url': {
            'dimensions': 'ga:pagePath',
            'filters': 'ga:pageviews!=0',
            'max_results': '10000',
            },
        'author': {
            'dimensions': 'ga:dimension2',
            'max_results': '100',
            },
        }

def get_pvs(service, profile_id, start_date, end_date, type, data):
    if type in TYPE_SETTINGS:
        return service.data().ga().get(
                ids = 'ga:' + profile_id,
                start_date = start_date,
                end_date = end_date,
                metrics = 'ga:pageviews',
                sort = '-ga:pageviews',
                **TYPE_SETTINGS[type]).execute()

如果您需要在将来定义更多TYPE_SETTINGS而不是typeurl,则可以轻松修改author