python - AWS Glue 中的可选作业参数?
问题描述
如何为 AWS Glue 作业实施可选参数?
我创建了一个当前具有字符串参数(ISO 8601 日期字符串)作为 ETL 作业中使用的输入的作业。我想将此参数设为可选,以便作业在未提供时使用默认值(例如,在我的情况下使用datetime.now和datetime.isoformat)。我试过使用getResolvedOptions:
import sys
from awsglue.utils import getResolvedOptions
args = getResolvedOptions(sys.argv, ['ISO_8601_STRING'])
但是,当我没有传递--ISO_8601_STRING
作业参数时,我看到以下错误:
awsglue.utils.GlueArgumentError:参数 --ISO_8601_STRING 是必需的
解决方案
如果您只有一个可选字段,matsev和Yuriy解决方案很好。
我为 python 编写了一个更通用的包装函数,可以处理不同的极端情况(必填字段和/或带有值的可选字段)。
import sys
from awsglue.utils import getResolvedOptions
def get_glue_args(mandatory_fields, default_optional_args):
"""
This is a wrapper of the glue function getResolvedOptions to take care of the following case :
* Handling optional arguments and/or mandatory arguments
* Optional arguments with default value
NOTE:
* DO NOT USE '-' while defining args as the getResolvedOptions with replace them with '_'
* All fields would be return as a string type with getResolvedOptions
Arguments:
mandatory_fields {list} -- list of mandatory fields for the job
default_optional_args {dict} -- dict for optional fields with their default value
Returns:
dict -- given args with default value of optional args not filled
"""
# The glue args are available in sys.argv with an extra '--'
given_optional_fields_key = list(set([i[2:] for i in sys.argv]).intersection([i for i in default_optional_args]))
args = getResolvedOptions(sys.argv,
mandatory_fields+given_optional_fields_key)
# Overwrite default value if optional args are provided
default_optional_args.update(args)
return default_optional_args
用法 :
# Defining mandatory/optional args
mandatory_fields = ['my_mandatory_field_1','my_mandatory_field_2']
default_optional_args = {'optional_field_1':'myvalue1', 'optional_field_2':'myvalue2'}
# Retrieve args
args = get_glue_args(mandatory_fields, default_optional_args)
# Access element as dict with args[‘key’]