Skip to content

Commit 1b73120

Browse files
add decorator for json rest endpoints
1 parent 112015c commit 1b73120

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

setup.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,8 @@ def run(self):
143143

144144
packages = ["splunklib",
145145
"splunklib.modularinput",
146-
"splunklib.searchcommands"],
146+
"splunklib.searchcommands",
147+
"splunklib.customrest"],
147148

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

splunklib/customrest/__init__.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
"""The following imports allow these classes to be imported via
2+
the splunklib.customrest package like so:
3+
4+
from splunklib.customrest import *
5+
"""
6+
from .json import json_handler

splunklib/customrest/json.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import logging
2+
import traceback
3+
import json
4+
5+
from functools import wraps
6+
7+
def json_handler(func):
8+
@wraps(func)
9+
def wrapper(*args, **kwargs):
10+
decorated = json_exception_handler(json_payload_extractor(func))
11+
return decorated(*args, **kwargs)
12+
return wrapper
13+
14+
15+
def json_payload_extractor(func):
16+
@wraps(func)
17+
def wrapper(self, in_string):
18+
try:
19+
request = json.loads(in_string)
20+
kwargs = {'request': request, 'in_string': in_string}
21+
if 'payload' in request:
22+
# if request contains payload, parse it and add it as payload parameter
23+
kwargs['payload'] = json.loads(request['payload'])
24+
if 'query' in request:
25+
# if request contains query, parse it and add it as query parameter
26+
kwargs['query'] = _convert_tuples_to_dict(request['query'])
27+
return func(self, **kwargs)
28+
except ValueError as e:
29+
return {'payload': {'success': 'false', 'result': f'Error parsing JSON: {e}'},
30+
'status': 400
31+
}
32+
return wrapper
33+
34+
35+
def json_exception_handler(func):
36+
@wraps(func)
37+
def wrapper(*args, **kwargs):
38+
try:
39+
return func(*args, **kwargs)
40+
except Exception as e:
41+
logging.error(
42+
f'error={repr(e)} traceback={traceback.format_exc()}')
43+
return {'payload': {'success': 'false', 'message': f'Error: {repr(e)}'},
44+
'status': 500
45+
}
46+
return wrapper
47+
48+
49+
def _convert_tuples_to_dict(tuples):
50+
return {t[0]: t[1] for t in tuples}
51+

0 commit comments

Comments
 (0)