amazon_cloud_service.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import boto3
  2. import os
  3. from tqdm.auto import tqdm
  4. import warnings
  5. from cloud_operations import Cloud_operations
  6. warnings.filterwarnings("ignore")
  7. class Amazon_cloud_operations(Cloud_operations):
  8. """Amazon cloud operations are derived class from Cloud_operations
  9. This class need credentials like aws_access_key, aws_secret_access_key, s3_bucket, region which is mandatory """
  10. def __init__(self, aws_access_key, aws_secret_access_key, s3_bucket,
  11. region):
  12. """Initializing all the needed credentials during object creation and validating it"""
  13. self.s3_file_name = os.path.split(each_file)[-1]
  14. self.__access_key = aws_access_key
  15. self.__secret_access_key = aws_secret_access_key
  16. self.__bucket = s3_bucket
  17. self.__region = region
  18. self.__s3_resource = None
  19. self.__validation_result = self.validate_login_credentials()
  20. print("Amazon S3 cloud operations started")
  21. def validate_login_credentials(self):
  22. """validate_login_credentials validates the given credentials from user, This method is from parent class Cloud_operations"""
  23. self.__s3_resource = boto3.client(service_name='s3',
  24. aws_access_key_id=self.__access_key,
  25. aws_secret_access_key=self.__secret_access_key,
  26. region_name=self.__region)
  27. try:
  28. self.__s3_resource.head_bucket(
  29. Bucket=self.__bucket) # try to validate credentials if success method return true else stop here
  30. print("Amazon S3 cloud Authentication set success")
  31. return True
  32. except Exception as e:
  33. raise e
  34. def upload_files(self, list_of_files):
  35. """upload_files on success of validation, this method uploads the give list of files to s3 bucket"""
  36. if self.__validation_result:
  37. self.count = 0 # local variable which tells count of files uploaded in S3 Buckets
  38. print(
  39. "Sample of file to be uploaded to S3 Buckets are \t {} ".format(
  40. list_of_files[:20]))
  41. for each_file in tqdm(list_of_files):
  42. try:
  43. self.__s3_resource = boto3.resource(service_name='s3',
  44. aws_access_key_id=self.__access_key,
  45. aws_secret_access_key=self.__secret_access_key,
  46. region_name=self.__region)
  47. self.__s3_resource.Bucket(self.__bucket).upload_file(
  48. Filename=each_file, Key=self.s3_file_name)
  49. # .upload_file from boto3 package uploads file to s3
  50. self.count += 1
  51. except Exception as e:
  52. print("Failed to upload file\n {}".format(each_file, e))
  53. else:
  54. print("please update the credentials to proceed further")
  55. print("Total file successfully uploaded:\t {}".format(self.count))
  56. return True