Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom response handler for automatic.com responses received by the REST API Modular Input Add-on for Splunk
import json
import requests
#the default handler , does nothing , just passes the raw output directly to STDOUT
class DefaultResponseHandler:
def __init__(self,**args):
pass
def __call__(self, response_object,raw_response_output,response_type,req_args,endpoint):
cookies = response_object.cookies
if cookies:
req_args["cookies"] = cookies
print_xml_stream(raw_response_output)
class AutomaticEventHandler:
def __init__(self,**args):
pass
def __call__(self, response_object,raw_response_output,response_type,req_args,endpoint):
if response_type == "json":
last_end_time = 0
#process the response from the orginal request
end_time = process_automatic_response(raw_response_output)
#set the latest end_time
if end_time > last_end_time:
last_end_time = end_time
#follow any pagination links in the response
next_link = response_object.links["next"]
while next_link:
next_response = requests.get(next_link)
end_time = process_automatic_response(next_response.text)
#set the latest end_time
if end_time > last_end_time:
last_end_time = end_time
next_link = next_response.links["next"]
if not "params" in req_args:
req_args["params"] = {}
#set the start URL attribute for the next request
#the Mod Input will persist this to inputs.conf for you
req_args["params"]["start"] = last_end_time
else:
print_xml_stream(raw_response_output)
#process the received JSON array
def process_automatic_response(data):
output = json.loads(data)
last_end_time = 0
for event in output:
#each element of the array is written to Splunk as a seperate event
print_xml_stream(json.dumps(event))
if "end_time" in event:
#get and set the latest end_time
end_time = event["end_time"]
if end_time > last_end_time:
last_end_time = end_time
return last_end_time
# prints XML stream
def print_xml_stream(s):
print "<stream><event unbroken=\"1\"><data>%s</data><done/></event></stream>" % encodeXMLText(s)
def encodeXMLText(text):
text = text.replace("&", "&amp;")
text = text.replace("\"", "&quot;")
text = text.replace("'", "&apos;")
text = text.replace("<", "&lt;")
text = text.replace(">", "&gt;")
text = text.replace("\n", "")
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.