我正在尝试在NiFi中创建一个Python脚本,实现以下功能:
- 从传入的flowfile中读取一些属性
- 读取flowfile的json内容并提取特定字段
- 将属性写入传出的flowfile
- 用脚本创建新的内容(例如返回新的JSON的API调用)覆盖原来的传入flowfile,并将其发送到成功关系,或删除旧的flowfile并创建想要的新内容。
目前为止,我已经完成了以下工作:
import json
import java.io
from org.apache.commons.io import IOUtils
from java.nio.charset import StandardCharsets
from org.apache.nifi.processor.io import StreamCallback,InputStreamCallback, OutputStreamCallback
class OutputWrite(OutputStreamCallback, obj):
def __init__(self):
self.obj = obj
def process(self, outputStream):
outputStream.write(bytearray(json.dumps(self.obj).encode('utf')))
###end class###
flowfile = session.get()
if flowfile != None:
**#1) Get flowfile attributes**
headers = {
'Accept-Encoding': 'gzip, deflate, br',
'Accept': 'application/json, text/plain, */*',
'Cache-Control': 'no-cache',
'Ocp-Apim-Trace': 'true',
'Authorization': flowfile.getAttribute('Authorization')
}
collection = flowfile.getAttribute('collection')
dataset = flowfile.getAttribute('dataset')
**#2)Get flowfile content**
stream_content = session.read(flowfile)
text_content = IOUtils.toString(stream_content, StandardCharsets.UTF_8)
json_content = json.loads(text_content)
records = json_content['result']['count']
pages = records/10000
**#3) Write flowfile attributes**
flowfile = session.putAttribute(flowfile, 'collection', collection)
flowfile = session.putAttribute(flowfile, 'dataset', dataset)
**#API operations: output_json with desired data**
output_json = {some data}
**#4) Write final JSON data to output flowfile**
flowfile = session.write(flowfile, OutputWrite(output_json))
session.transfer(flowfile, REL_SUCCESS)
session.commit()
我的问题是我找不到一种方法将所需的output_json对象的引用作为参数传递给OutputStreamCallback类。有什么解决方法或更好的方法吗?
也许在这种情况下,在类的process函数中执行所有API操作会更容易,但是如何在process函数中获取流入flowfile属性的访问权限(需要会话或flowfile对象)?
非常感谢任何帮助!