Nifi: How to pass Python's output from ExecuteScript to PutEmail body without writing to a file

Viewed 949

I'm very new to Nifi and I was wondering if I can pass Python's output (stdout,pandas df,markdown) from ExecuteScript without writing the output to a file in order to send out an email with PutEmail as part of the body in the email. Thank you in advance.

1 Answers

Yes, you can do that by writing to the flowfile in your ExecuteScript. E.g.:

from org.apache.commons.io import IOUtils
from java.nio.charset import StandardCharsets
from org.apache.nifi.processor.io import StreamCallback

# Define a subclass of StreamCallback for use in session.write()
class PyStreamCallback(StreamCallback):
    def __init__(self):
        pass
    def process(self, inputStream, outputStream):
      # Write to flowfile
      out = IOUtils.toString(inputStream, StandardCharsets.UTF_8) + ' Bar'
      outputStream.write(bytearray(out.encode('utf-8')))
# end class

flowFile = session.get()
if(flowFile != None):
    try:
        flowFile = session.write(flowFile, PyStreamCallback())
        # Last operation is transfer to success (failures handled in the catch block)
        session.transfer(flowFile, REL_SUCCESS)
    except Exception as e:
        log.error(repr(e))
        session.transfer(flowFile, REL_FAILURE)
# implicit return at the end

I tested it with following flow:

enter image description here

I set GenerateFlowFile Custom Text to Foo, let ExecuteScript add Bar to it and write the result to the flowfile. Same applies to your use case. Simply let your script write content to the flowfile. PutEmail will take this content and send it via email.

Learn how to master ExecuteScript: https://community.cloudera.com/t5/Community-Articles/ExecuteScript-Cookbook-part-1/ta-p/248922

Related