From f53715d4dde8fb0ee74e71ae85d20f1676d2458f Mon Sep 17 00:00:00 2001 From: Cristian Pana Date: Thu, 4 Jul 2024 11:16:42 +0300 Subject: [PATCH] Read response HTTP status when doing API Upload before trying to parse JSON --- workbench-agent.py | 49 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/workbench-agent.py b/workbench-agent.py index 35ca6ca..80883d7 100755 --- a/workbench-agent.py +++ b/workbench-agent.py @@ -107,6 +107,7 @@ def upload_files(self, scan_code: str, path: str, enable_chunk_upload: bool = Tr # Use chunked upload for files bigger than size_limit # First delete possible existing files because chunk uploading works by appending existing file on disk. self.remove_uploaded_content(filename, scan_code) + print(f"Uploading...") headers = { "FOSSID-SCAN-CODE": scan_code_base64, "FOSSID-FILE-NAME": filename_base64, @@ -121,11 +122,25 @@ def upload_files(self, scan_code: str, path: str, enable_chunk_upload: bool = Tr auth=(self.api_user, self.api_token), timeout=1800, ) - try: - resp.json() - except: - print(f"Failed to decode json {resp.text}") - print(traceback.print_exc()) + # Retrieve the HTTP status code + status_code = resp.status_code + print(f"HTTP Status Code: {status_code}") + + # Check if the request was successful (status code 200) + if status_code == 200: + # Parse the JSON response + try: + resp.json() + except: + print(f"Failed to decode json {resp.text}") + print(traceback.print_exc()) + sys.exit(1) + else: + print(f"Request failed with status code {status_code}") + reason = resp.reason + print(f"Reason: {reason}") + response_text = resp.text + print(f"Response Text: {response_text}") sys.exit(1) except IOError: # Error opening file @@ -147,11 +162,25 @@ def upload_files(self, scan_code: str, path: str, enable_chunk_upload: bool = Tr auth=(self.api_user, self.api_token), timeout=1800, ) - try: - resp.json() - except: - print(f"Failed to decode json {resp.text}") - print(traceback.print_exc()) + # Retrieve the HTTP status code + status_code = resp.status_code + print(f"HTTP Status Code: {status_code}") + + # Check if the request was successful (status code 200) + if status_code == 200: + # Parse the JSON response + try: + resp.json() + except: + print(f"Failed to decode json {resp.text}") + print(traceback.print_exc()) + sys.exit(1) + else: + print(f"Request failed with status code {status_code}") + reason = resp.reason + print(f"Reason: {reason}") + response_text = resp.text + print(f"Response Text: {response_text}") sys.exit(1) except IOError: # Error opening file