Skip to content

Commit 4ba3eae

Browse files
author
Ryan Causey
committed
FEATURE: Allow json data to be posted directly via the webservice
1 parent 4342a3c commit 4ba3eae

2 files changed

Lines changed: 201 additions & 147 deletions

File tree

common/src/stack/ws-client/pylib/wsclient.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import requests
1111

1212
import json
13+
import re
1314
from stack.bool import str2bool
1415

1516
import http.client
@@ -39,7 +40,7 @@ def login(self):
3940

4041
csrftoken = resp.cookies['csrftoken']
4142
self.session.headers.update({
42-
"csrftoken":csrftoken,
43+
"csrftoken":csrftoken,
4344
"X-CSRFToken":csrftoken,
4445
})
4546
resp = self.session.post("%s/login" % self.url,
@@ -56,17 +57,24 @@ def login(self):
5657
"sessionid":self.sessionid,
5758
})
5859
self.logged_in = True
59-
60+
6061
def run(self, cmd):
62+
data = None
6163
if not self.logged_in:
6264
self.login()
63-
if cmd.startswith('load ') or \
64-
cmd.startswith('unload '):
65+
if (cmd.startswith('load ') or cmd.startswith('unload ')) and "json-file=" not in cmd:
6566
new_cmd = self.loadFile(cmd)
6667
cmd = new_cmd
68+
elif cmd.startswith('load '):
69+
regex = r"json-file=(?P<filename>\w+.\w+)"
70+
file_match = re.search(regex, cmd)
71+
if file_match:
72+
cmd = re.sub(regex, "", cmd)
73+
with open(file_match.group("filename")) as json_file:
74+
data = json.load(json_file)
6775

6876
self.session.headers.update({"Content-Type": "application/json"})
69-
js = json.dumps({"cmd":cmd})
77+
js = json.dumps({"cmd":cmd, "data":data}) if data else json.dumps({"cmd":cmd})
7078
resp = self.session.post(self.url, data = js)
7179
try:
7280
out = json.loads(resp.json())
@@ -96,10 +104,10 @@ def loadFile(self, cmd):
96104
def upload(self, filename):
97105
if not os.path.exists(filename) or not os.path.isfile(filename):
98106
raise IOError(f'File {filename} does not exist')
99-
107+
100108
if 'Content-Type' in self.session.headers:
101109
del self.session.headers['Content-Type']
102-
110+
103111
response = self.session.post(f'{self.url}/upload', files={
104112
'csvFile': (os.path.basename(filename), open(filename, 'rb'), 'text/csv')
105113
})

0 commit comments

Comments
 (0)