我正在尝试将xcom值传递给普通功能,但它正在传递实际值
我在下面使用示例代码尝试了
def getArgsForPractice(practice, messageId, status_result):
practice_args = dict()
practice_args['practice_id'] = practice
practice_args['message_id'] = messageId
practice_args['status'] = status_result
practice_args_json = json.dumps(practice_args)
message = {'data': base64.b64encode(practice_args_json.encode('utf-8')).decode()}
return message
PubSubPublishSuccess = PubSubPublishOperator(task_id='publish-messages_success',
topic=PUB_SUB_TOPIC,
project=PROJECT_ID,
messages=[
getArgsForPractice(
"{{ task_instance.xcom_pull('get_practice_id_task', key='return_value')[0]}}",
"{{ task_instance.xcom_pull('get_measure_id_task', key='return_value')[0]}}",
"SUCCESS"
)
],
dag=dag)
我在下面看到了如下所示的输出值:
{"practice_id": "{{ task_instance.xcom_pull('get_practice_id_task', key='return_value')[0]}}", "message_id": "{{ task_instance.xcom_pull('get_measure_id_task', key='return_value')[0]}}", "status": "SUCCESS"} │ 599454601822320 │
答案 0 :(得分:0)
之所以会出现问题,是因为首先使用您传递的任何参数调用了函数getArgsForPractice
。输出将作为模板字段发送给操作员。由于您的函数输出是经过base64编码的,因此操作员无法在其中找到任何模板变量。
解决方案是在两者之间使用PythonOperator解析数据并以所需格式获取数据。请参阅下面的代码。
def getArgsForPractice(**context):
practice = context.get('ti').xcom_pull('get_practice_id_task')[0]
messageId = context.get('ti').xcom_pull('get_measure_id_task')[0]
practice_args = dict()
practice_args['practice_id'] = practice
practice_args['message_id'] = messageId
practice_args['status'] = "SUCCESS"
practice_args_json = json.dumps(practice_args)
message = base64.b64encode(practice_args_json.encode('utf-8')).decode()
return message
middle_task = PythonOperator(
dag=dag,
task_id='middle_task',
python_callable=getArgsForPractice,
provide_context=True
)
PubSubPublishSuccess = PubSubPublishOperator(task_id='publish-messages_success',
topic=PUB_SUB_TOPIC,
project=PROJECT_ID,
messages=[{"data": "{{task_instance.xcom_pull('middle_task')}}"}],
dag=dag)
middle_task >> PubSubPublishSuccess
发现我没有在任何xcom_pull上使用key='return_value'
,因为它是默认的。