Skip to content

Commit 2fdb8f1

Browse files
Birger SchachtBirger Schacht
authored andcommitted
FIX: fix json output and add error handling
Hug can not simply return a string that contains json. Therefore the content of the files first has to converted to a JSON object. This commit also implements simple error handling in case the files do not exists or can not be created. Closes: #14
1 parent 077146d commit 2fdb8f1

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

intelmq_api/api.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
IntelMQ-Manager. The logic itself is in the runctl & files modules.
1212
"""
1313

14+
import json
1415
import sys
1516
import os
1617
import pathlib
@@ -196,11 +197,15 @@ def login(username: str, password: str):
196197

197198
@hug.get("/api/harmonization", requires=token_authentication, versions=1)
198199
def get_harmonization():
199-
positions = pathlib.Path('/opt/intelmq/etc/harmonization.conf')
200+
harmonization = pathlib.Path('/opt/intelmq/etc/harmonization.conf')
200201
paths = runner.get_paths()
201202
if 'CONFIG_DIR' in paths:
202-
positions = pathlib.Path(paths['CONFIG_DIR']) / 'harmonization.conf'
203-
return positions.read_text()
203+
harmonization = pathlib.Path(paths['CONFIG_DIR']) / 'harmonization.conf'
204+
try:
205+
return json.loads(harmonization.read_text())
206+
except OSError as e:
207+
print(f"Could not read {harmonization}: {str(e)}")
208+
return {}
204209

205210

206211
@hug.get("/api/runtime", requires=token_authentication, versions=1)
@@ -219,7 +224,11 @@ def get_positions():
219224
paths = runner.get_paths()
220225
if 'CONFIG_DIR' in paths:
221226
positions = pathlib.Path(paths['CONFIG_DIR']) / 'manager/positions.conf'
222-
return positions.read_text()
227+
try:
228+
return json.loads(positions.read_text())
229+
except OSError as e:
230+
print(f"Could not read {positions}: {str(e)}")
231+
return {}
223232

224233

225234
@hug.post("/api/positions", requires=token_authentication, version=1)
@@ -228,5 +237,10 @@ def post_positions(body):
228237
paths = runner.get_paths()
229238
if 'CONFIG_DIR' in paths:
230239
positions = pathlib.Path(paths['CONFIG_DIR']) / 'manager/positions.conf'
231-
positions.write_text(body)
232-
return positions.read_text()
240+
try:
241+
positions.parent.mkdir(exist_ok=True)
242+
positions.write_text(json.dumps(body, indent=4))
243+
return json.loads(positions.read_text())
244+
except OSError as e:
245+
print(f"Error creating {positions.parent} or writing to {positions}: {str(e)}")
246+
return {}

0 commit comments

Comments
 (0)