s3upload_boto_1.py 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. def upload_file(s3, bucketname, file_path):
  2. b = s3.get_bucket(bucketname)
  3. filename = os.path.basename(file_path)
  4. k = b.new_key(filename)
  5. mp = b.initiate_multipart_upload(filename)
  6. source_size = os.stat(file_path).st_size
  7. bytes_per_chunk = 5000*1024*1024
  8. chunks_count = int(math.ceil(source_size / float(bytes_per_chunk)))
  9. for i in range(chunks_count):
  10. offset = i * bytes_per_chunk
  11. remaining_bytes = source_size - offset
  12. bytes = min([bytes_per_chunk, remaining_bytes])
  13. part_num = i + 1
  14. print( "uploading part " + str(part_num) + " of " + str(chunks_count))
  15. with open(file_path, 'r') as fp:
  16. fp.seek(offset)
  17. mp.upload_part_from_file(fp=fp, part_num=part_num, size=bytes)
  18. if len(mp.get_all_parts()) == chunks_count:
  19. mp.complete_upload()
  20. print ("upload_file done")
  21. else:
  22. mp.cancel_upload()
  23. print ("upload_file failed")