首页 > 解决方案 > 如何为具有附加功能的函数创建装饰器?

问题描述

我想重构我的代码。我目前正在做的是从广告平台 API 端点提取数据并将其转换并上传到大查询。我有以下有效的代码,但我想在了解装饰器后对其进行重构。

装饰器是 Python 中非常强大和有用的工具,因为它允许程序员修改函数或类的行为。装饰器允许我们包装另一个函数以扩展包装函数的行为,而无需永久修改它。

import datauploader
import ndjson
import os

def upload_ads_details(extractor, access_token, acccount_id, req_output, 
                       bq_client_name, bq_dataset_id, bq_gs_bucket, 
                       ndjson_local_file_path, ndjson_file_name):


    # Function to Extract data from the API/Ad Platform
    ads_dictionary = extractor.get_ad_dictionary(access_token, acccount_id)

    # Converting data to ndjson for upload to big query
    output_ndjson = ndjson.dumps(ads_dictionary)
    with open(ndjson_local_file_path, 'w') as f:
        f.writelines(output_ndjson)
    print(os.path.abspath(ndjson_local_file_path))

    # This code below remains the same for all the other function calls
    if req_output:
        # Inputs for the uploading functions
        print("Processing Upload")
        partition_by = "_insert_time"
        str_gcs_file_name = ndjson_file_name
        str_local_file_name = ndjson_local_file_path
        gs_bucket = bq_gs_bucket
        gs_file_format = "JSON"
        table_id = 'ads_performance_stats_table'
        table_schema = ads_dictionary_schema

        # Uploading Function
        datauploader.loadToBigQuery(
            bq_client_name,
            bq_dataset_id,
            table_id,
            table_schema,
            partition_by,
            str_gcs_file_name,
            str_local_file_name,
            gs_bucket,
            gs_file_format,
            autodetect=False,
            req_partition=True,
            skip_leading_n_row=0
        )



标签: pythonpython-3.x

解决方案


推荐阅读