boto-updater.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import boto3
  2. from botocore.exceptions import ClientError
  3. import os.path
  4. # Arguments
  5. folder_to_sync = './test/data'
  6. bucket_target = 'my-bucket'
  7. # Create connection
  8. s3 = boto3.client('s3', use_ssl=False, endpoint_url="http://172.17.0.2:9000", aws_access_key_id="minio", aws_secret_access_key="miniokey")
  9. # Check bucket
  10. try:
  11. s3.head_bucket(Bucket=bucket_target)
  12. except ClientError as e:
  13. print('Create bucket', bucket_target)
  14. s3.create_bucket(Bucket=bucket_target)
  15. # Get file list
  16. # Source : https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
  17. local_file_list = os.listdir(folder_to_sync)
  18. try:
  19. bucket_file_list = [obj['Key'] for obj in s3.list_objects(Bucket=bucket_target)['Contents']]
  20. except:
  21. bucket_file_list = [] # No key 'Contents' if empty bucket
  22. # Upload
  23. print("Uploading new files ...")
  24. for file_name in local_file_list:
  25. print(file_name, end=' ')
  26. file_path = folder_to_sync + '/' + file_name
  27. if file_name in bucket_file_list:
  28. # Todo : compare modification dates
  29. print('(Not updated)')
  30. elif os.path.isfile(file_path):
  31. res = s3.upload_file(file_path, bucket_target, file_name)
  32. print('(New file)')
  33. else:
  34. print('(Skipped)')
  35. print("Done")
  36. # Delete files
  37. print("Deleting removed files ...")
  38. for file_name in bucket_file_list:
  39. print(file_name, end=' ')
  40. if file_name in local_file_list:
  41. print('(Still present)')
  42. else:
  43. s3.delete_object(Bucket=bucket_target, Key=file_name)
  44. print('(Deleted)')
  45. print("Done")