From 8ac99f9a0307d85ca7f67fc7f69abeecfb0a9838 Mon Sep 17 00:00:00 2001 From: "marcus.v.d.veloso" Date: Tue, 4 Mar 2025 02:30:19 +0000 Subject: [PATCH] reviewing code with ai tool --- api_client.py | 57 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/api_client.py b/api_client.py index 6aa2068..b7fe12e 100644 --- a/api_client.py +++ b/api_client.py @@ -4,6 +4,42 @@ import click import requests +import urllib.parse + + +API_ENDPOINT = '/api' +VERSION = '1.1.4' + + +def is_valid_url(url): + """ + Checks if a given URL is valid and reachable. + + Args: + url (str): The URL to check. + + Returns: + bool: True if the URL is valid and reachable, False otherwise. + """ + try: + result = urllib.parse.urlparse(url) + # Try to reach url with a `HEAD` call + response = requests.head(url) + response.raise_for_status() + return all([result.scheme, result.netloc]) + + except (ValueError, requests.exceptions.RequestException): + return False + +def exit_with_error(message): + """ + Prints an error message and exits the program with a non-zero exit code. + + Args: + message (str): The error message to print. + """ + print(f"Error: {message}") + sys.exit(1) @click.command() @@ -23,22 +59,25 @@ def main(file_path, host_url): # check if file path folder exist if not os.path.isfile(file_path): - print('Error: File', file_path, 'does not exist!') - sys.exit(1) - # ToDo: check if the `host_url` is a valid URL + exit_with_error(f"File {file_path} does not exist!") + + # check if the `host_url` is a valid URL + if not is_valid_url(host_url): + exit_with_error(f"Invalid URL or unreachable host: {host_url}") # try to upload the file - with open(file_path, 'rb') as file: - req = requests.post(host_url + '/api', files={'file': open(file_path, 'rb')}) - if req.status_code == 200: + try: + with open(file_path, 'rb') as file: #Opens the file in binary read mode `rb` to ensure proper handling of different file types + req = requests.post(host_url + API_ENDPOINT, files={'file': file}) + req.raise_for_status() #Raise an exception for bad status code print('File ', file_path, 'was uploaded with success to ', host_url) - else: - print('Upload failed') + except requests.exceptions.RequestException as e: + exit_with_error(f"Error during upload: {e}") if __name__ == '__main__': print("------------------------------") - print("API Manual Upload File v-1.1.3") + print(f"API Manual Upload File v-{VERSION}") print("Date/Time: {}".format(time.asctime(time.localtime(time.time())))) print("------------------------------")