Skip to main content

Upload File to S3

Description

The upload_file_to_s3 function uploads a file to an S3 bucket using a signed URL. It includes automatic retries for failed attempts, up to 5 retries.

Function Signature:

def upload_file_to_s3(file_path: str, signed_url: str) -> int:

Parameters

  • file_path (str): The local path of the file to be uploaded.
  • signed_url (str): The signed URL provided by the S3 service that allows the file upload.

Returns

  • int: The result of the upload operation:
    • 0: Success
    • -1: Error uploading file (non-200 status code)
    • -2: Exception occurred while uploading file
    • -3: Retry limit exceeded

Example Usage

file_path = "path/to/your/file.txt"
signed_url = "https://your-bucket.s3.amazonaws.com/your-object?signature=xyz"
result = upload_file_to_s3(file_path, signed_url)

if result == 0:
print("File uploaded successfully")
else:
print(f"File upload failed with result code: {result}")

Notes

  • The function tries to upload the file up to 5 times in case of failure (based on non-200 status code or exception).
  • If the retry count exceeds 5, the function returns -3.
  • If an exception occurs during the file upload (e.g., network issues), the function will catch it, print the error, and attempt to retry after a short delay.
  • The retry mechanism can be useful for handling intermittent network issues or temporary server unavailability.

Error Handling

  • If the upload returns a non-200 status code, it prints an error and retries the upload.
  • If an exception occurs during the upload, it prints the exception message and retries the upload.