spaces.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env python3
  2. import os
  3. import json
  4. import time
  5. import logging
  6. from colors import color
  7. from boto3 import session
  8. from cli_tools import parser
  9. from utils import ProgressPercentage
  10. from config import (ACCESS_ID,SECRET_KEY,SERVICE_NAME,REGION_NAME,ENDPOINT_URL,BUCKET_NAME)
  11. cwd_dir = os.getcwd()
  12. logs_dir = os.path.join(cwd_dir, '.logs')
  13. failed_dir = os.path.join(cwd_dir, '.failed_uploads')
  14. if not os.path.exists(logs_dir):
  15. os.makedirs(logs_dir)
  16. logging.basicConfig(filename=os.path.join(logs_dir,'logs.log'),
  17. filemode='a',format='%(asctime)s %(levelname)s %(message)s',
  18. )
  19. if not os.path.exists(failed_dir):
  20. os.makedirs(failed_dir)
  21. def log_error(error_file):
  22. log_file = os.path.join(failed_dir,"%s.txt"%time.strftime("%Y%m%d"))
  23. if not os.path.exists(log_file):
  24. with open(log_file, 'w'):
  25. pass
  26. with open(log_file, 'a') as f:
  27. f.write(error_file)
  28. # Initiate session
  29. session = session.Session()
  30. def set_client():
  31. client = session.client(
  32. service_name=SERVICE_NAME,
  33. region_name=REGION_NAME,
  34. endpoint_url=ENDPOINT_URL,
  35. aws_access_key_id=ACCESS_ID,
  36. aws_secret_access_key=SECRET_KEY
  37. )
  38. return client
  39. def upload_dir(dirpath,bucket_name=None):
  40. client = set_client()
  41. if not os.path.isdir(dirpath):
  42. raise Exception("Not a Valid Directory :%s" % (dirpath))
  43. bucket = BUCKET_NAME
  44. if bucket_name:
  45. bucket = bucket_name
  46. file_count = 0
  47. error_count = 0
  48. print(color("Initializing ...\n",fg="yellow"))
  49. for (root, dirs, filenames) in os.walk(top=dirpath, topdown=True):
  50. for filename in filenames:
  51. filepath = os.path.join(root, filename)
  52. try:
  53. print(color("%s \nuploading...\n"%filepath,fg='blue'))
  54. client.upload_file(filepath, bucket ,os.path.abspath(filepath) ,Callback=ProgressPercentage(filepath))
  55. print(color("Success\n",fg="lime"))
  56. file_count += 1
  57. except Exception as e:
  58. logging.error('FilePath: %s' % filepath, exc_info=True)
  59. error_count += 1
  60. print(color("Error encountered: %s"%e,fg="#ff1a1a"))
  61. log_error("%s\n"%filepath)
  62. continue
  63. print(color("Total number of files uploaded: %d.\n" % file_count,fg="lime"))
  64. print(color("Total number of errors encountered: %d." % error_count,fg="#ff1a1a"))
  65. if error_count > 1:
  66. print(color("Please Check the log file located at .logs in the current working directory",fg='#ff1a1a'))
  67. if __name__ == '__main__':
  68. args = parser.parse_args()
  69. root_dir = args.dir
  70. bucket_name = args.bucket
  71. upload_dir(root_dir,bucket_name)