在上一篇文章对Nifi与ExecuteScript进行了简单的介绍,已经提供了关于如何用Python对Flowfile内容进行修改的案例。
接下来将介绍如何在ExecuteScript中采用Python来修改Flowfile的属性。
案例:采用Python来修改Flowfile属性
以下案例会采用GenerateFlowFile处理器生成一个Flowfile,该Flowfile有一个Age属性,初始值为26, 之后会采用ExecuteScript读取该Age属性,并对其加1,然后再更新到Flowfile的Age属性。并且会增加多一个Gender的属性进行输出。
拓扑图:
GenerateFlowFile设置:
添加了Age属性,初始值为26
ExecuteScript处理器设置:
ScriptBody为:
import json
import sys
import traceback
from java.nio.charset import StandardCharsets
from org.apache.commons.io import IOUtils
from org.apache.nifi.processor.io import StreamCallback
from org.python.core.util import StringUtil
from datetime import datetime
flowFile = session.get()
if flowFile != None:
try:
#Get the attribute from Flowfile
Age = flowFile.getAttribute("Age")
Age = int(Age) + 1
flowFile = session.putAttribute(flowFile, "Age", str(Age))
#Add a new attribute
flowFile = session.putAttribute(flowFile, "Gender", "Male")
session.transfer(flowFile, REL_SUCCESS)
except Exception as e:
# Catch the exception and set it as an attribute
session.putAttribute(flowFile, "error", 'An error occurred, due to ' + str(e))
session.transfer(flowFile, REL_FAILURE)
输出结果:
一开始Flowfile的属性为:
经过ExcuteScript之后可以观察到Age变为了27并且添加了属性Gender,其值为Male