python - 如何为具有附加功能的函数创建装饰器?
问题描述
我想重构我的代码。我目前正在做的是从广告平台 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
)
解决方案
推荐阅读
- python - 导入 excel 工作簿中的每个工作表并保存到以工作表名称命名的数据框
- node.js - 对于这些场景,如何使用 Jest 为无服务器测试创建测试?
- kotlin - 如何在带有左方差注释的情况下对 vavr 进行 flatMap
- javascript - Select2 使用 jquery 隐藏选项
- python - 当我尝试使用 Python 连接 Teradata 时,它显示“当前无法通过此网络访问 Teradata 服务器”
- python - 数字和加号/减号的正则表达式
- python - 关于python中字典赋值的问题
- npm - 无论如何要检查 npm 包是否已从正确的分支发布?
- r - 在R编程中向上移动单元格
- java - 获取最后一个 ChannelInboundHandler 的结果