Skip to content

Commit 0cfe72c

Browse files
committedDec 14, 2024·
Only print JSON response of failed API requests
If the response is not valid JSON, do not print it to stdout and only log it to debug output.
1 parent 678d7a0 commit 0cfe72c

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed
 

‎submit/submit

+15-9
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,15 @@ def error(msg: str) -> NoReturn:
7070
exit(-1)
7171

7272

73+
def print_if_json(text: str):
74+
'''Print the text if it is valid JSON, and ignore otherwise'''
75+
try:
76+
data = json.loads(text)
77+
print(json.dumps(data, indent=2))
78+
except json.decoder.JSONDecodeError:
79+
pass
80+
81+
7382
def read_contests() -> list:
7483
'''Read all contests from the API.
7584
@@ -202,15 +211,14 @@ def do_api_request(name: str):
202211
except requests.exceptions.RequestException as e:
203212
raise RuntimeError(e)
204213

214+
logging.debug(f"API call '{name}' returned:\n{response.text}")
205215
if response.status_code >= 300:
206-
print(response.text)
216+
print_if_json(response.text)
207217
if response.status_code == 401:
208218
raise RuntimeError('Authentication failed, please check your DOMjudge credentials in ~/.netrc.')
209219
else:
210220
raise RuntimeError(f'API request {name} failed (code {response.status_code}).')
211221

212-
logging.debug(f"API call '{name}' returned:\n{response.text}")
213-
214222
return json.loads(response.text)
215223

216224

@@ -322,11 +330,10 @@ def do_api_print():
322330

323331
response = requests.post(url, data=data, headers=headers)
324332

325-
logging.debug(f"API call 'printing' returned:\n{response.text}")
326-
327333
# The connection worked, but we may have received an HTTP error
334+
logging.debug(f"API printing call returned:\n{response.text}")
328335
if response.status_code >= 300:
329-
print(response.text)
336+
print_if_json(response.text)
330337
if response.status_code == 401:
331338
raise RuntimeError('Authentication failed, please check your DOMjudge credentials in ~/.netrc.')
332339
else:
@@ -367,11 +374,10 @@ def do_api_submit():
367374

368375
response = requests.post(url, data=data, files=files, headers=headers)
369376

370-
logging.debug(f"API call 'submissions' returned:\n{response.text}")
371-
372377
# The connection worked, but we may have received an HTTP error
378+
logging.debug(f"API submitting call returned:\n{response.text}")
373379
if response.status_code >= 300:
374-
print(response.text)
380+
print_if_json(response.text)
375381
if response.status_code == 401:
376382
raise RuntimeError('Authentication failed, please check your DOMjudge credentials in ~/.netrc.')
377383
else:

0 commit comments

Comments
 (0)
Please sign in to comment.