Skip to content

Commit

Permalink
add decorator for json rest endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
marcusschiesser authored Jul 18, 2022
1 parent 112015c commit 1b73120
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ def run(self):

packages = ["splunklib",
"splunklib.modularinput",
"splunklib.searchcommands"],
"splunklib.searchcommands",
"splunklib.customrest"],

url="http://github.com/splunk/splunk-sdk-python",

Expand Down
6 changes: 6 additions & 0 deletions splunklib/customrest/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""The following imports allow these classes to be imported via
the splunklib.customrest package like so:
from splunklib.customrest import *
"""
from .json import json_handler
51 changes: 51 additions & 0 deletions splunklib/customrest/json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import logging
import traceback
import json

from functools import wraps

def json_handler(func):
@wraps(func)
def wrapper(*args, **kwargs):
decorated = json_exception_handler(json_payload_extractor(func))
return decorated(*args, **kwargs)
return wrapper


def json_payload_extractor(func):
@wraps(func)
def wrapper(self, in_string):
try:
request = json.loads(in_string)
kwargs = {'request': request, 'in_string': in_string}
if 'payload' in request:
# if request contains payload, parse it and add it as payload parameter
kwargs['payload'] = json.loads(request['payload'])
if 'query' in request:
# if request contains query, parse it and add it as query parameter
kwargs['query'] = _convert_tuples_to_dict(request['query'])
return func(self, **kwargs)
except ValueError as e:
return {'payload': {'success': 'false', 'result': f'Error parsing JSON: {e}'},
'status': 400
}
return wrapper


def json_exception_handler(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
logging.error(
f'error={repr(e)} traceback={traceback.format_exc()}')
return {'payload': {'success': 'false', 'message': f'Error: {repr(e)}'},
'status': 500
}
return wrapper


def _convert_tuples_to_dict(tuples):
return {t[0]: t[1] for t in tuples}

0 comments on commit 1b73120

Please sign in to comment.