ossUtils.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import oss2
  2. import traceback
  3. from utils.Utils import log
  4. import time
  5. import os
  6. def does_bucket_exist(bucket):
  7. try:
  8. bucket.get_bucket_info()
  9. except oss2.exceptions.NoSuchBucket:
  10. return False
  11. except:
  12. raise
  13. return True
  14. import hashlib
  15. def getMDFFromFile(path):
  16. _length = 0
  17. try:
  18. _md5 = hashlib.md5()
  19. with open(path,"rb") as f:
  20. while True:
  21. data = f.read(4096)
  22. if not data:
  23. break
  24. _length += len(data)
  25. _md5.update(data)
  26. return _md5.hexdigest(),_length
  27. except Exception as e:
  28. traceback.print_exc()
  29. return None,_length
  30. def uploadFileByPath(bucket,filepath,uploadpath,headers=None):
  31. try:
  32. start_time = time.time()
  33. log("uploading file of %s"%filepath)
  34. with open(filepath,"rb") as f:
  35. bucket.put_object(uploadpath,f,headers=headers)
  36. log("upload file of %s takes %ds"%(filepath,time.time()-start_time))
  37. return True
  38. except Exception as e:
  39. traceback.print_exc()
  40. log("upload object failed of %s"%(filepath))
  41. return False
  42. def deleteObject(bucket,objectName):
  43. try:
  44. bucket.delete_object(objectName)
  45. except Exception as e:
  46. log("delete object failed of %s"%objectName)
  47. def downloadFile(bucket,objectPath,localPath):
  48. try:
  49. # bucket.get_object_to_file(objectPath, localPath)
  50. oss2.resumable_download(bucket, objectPath, localPath,
  51. store=oss2.ResumableDownloadStore(root=os.path.join(os.path.dirname(__file__),"/../tmp")),
  52. multiget_threshold=200*1024,
  53. part_size=200*1024,
  54. num_threads=5)
  55. return True
  56. except Exception as e:
  57. log("download object failed of %s"%str(objectPath))
  58. return False
  59. if __name__=="__main__":
  60. print(getMDFFromFile('1578298842064.doc'))