Guest User

Untitled

a guest
Jan 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import os
  4. import logging
  5. from shutil import copyfileobj
  6.  
  7. logging.basicConfig(level=logging.DEBUG)
  8. log = logging.getLogger()
  9. # Reduce the logging level of botocore and boto3
  10. logging.getLogger('botocore').setLevel(logging.WARNING)
  11. logging.getLogger('boto3').setLevel(logging.WARNING)
  12.  
  13.  
  14. from django.conf import settings
  15. settings.configure()
  16.  
  17. import boto3
  18. from storages.backends.s3boto3 import S3Boto3Storage
  19.  
  20.  
  21. def mktestfile(filename):
  22. """Generates a ten megabyte text file with an incrementing counter."""
  23. desired_size = 10 * (2 ** 20)
  24. num_lines = desired_size // 64
  25. with open(filename, 'w') as f:
  26. for i in range(num_lines):
  27. # each line is 64 characters long, with leading whitespace
  28. # and the counter at the end. using 'sort -c' can confirm it's
  29. # in numeric order.
  30. f.write('%63d\n' % (i + 1))
  31.  
  32.  
  33. FN = 'test-file.txt'
  34. BUCKET = 'kx-tom-misc-test-bucket'
  35. if not os.path.exists(FN):
  36. log.info("Creating test file.")
  37. mktestfile(FN)
  38.  
  39. s3_storage = S3Boto3Storage(
  40. bucket=BUCKET
  41. )
  42.  
  43. original_size = os.stat(FN).st_size
  44. log.info("Size of '%s' is %d bytes. (%d megabytes)", FN, original_size, original_size // 2**20)
  45. dest_file = s3_storage.open(FN, 'wb')
  46. with open(FN, 'rb') as source_file:
  47. CHUNK_SIZE = 2 ** 20 # one megabyte
  48. log.info("Writing to %r in chunks of %d bytes (%d megabyte).", dest_file, CHUNK_SIZE, CHUNK_SIZE // 2**20)
  49. copyfileobj(source_file, dest_file, length=2**20)
  50. dest_file.close()
  51. log.info('Upload complete, checking size of file in S3 Bucket')
  52. s3_object_size = boto3.resource('s3').Bucket(BUCKET).Object(FN).content_length
  53. log.info("Size of 's3://%s/%s' is %d bytes. (%d megabytes)",
  54. BUCKET, FN, s3_object_size, s3_object_size // 2**20)
Add Comment
Please, Sign In to add comment