Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 48 additions & 9 deletions api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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("------------------------------")

Expand Down