upload-file 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env python
  2. """
  3. Uploads a file using s3transfer. You can also chose how type of file that
  4. is uploaded (i.e. filename, seekable, nonseekable).
  5. Usage
  6. =====
  7. NOTE: Make sure you run ``pip install -r requirements-dev.txt`` before running.
  8. To upload a file::
  9. ./upload-file --file-name myfilename --file-type filename \\
  10. --s3-bucket mybucket --s3-key mykey
  11. """
  12. import argparse
  13. from botocore.session import get_session
  14. from s3transfer.manager import TransferManager
  15. class NonSeekableReader:
  16. """A wrapper to hide the ability to seek for a fileobj"""
  17. def __init__(self, fileobj):
  18. self._fileobj = fileobj
  19. def read(self, amt=-1):
  20. return self._fileobj.read(amt)
  21. class Uploader:
  22. def upload(self, args):
  23. session = get_session()
  24. client = session.create_client('s3')
  25. file_type = args.file_type
  26. if args.debug:
  27. session.set_debug_logger('')
  28. with TransferManager(client) as manager:
  29. getattr(self, 'upload_' + file_type)(
  30. manager, args.file_name, args.s3_bucket, args.s3_key
  31. )
  32. def upload_filename(self, manager, filename, bucket, s3_key):
  33. manager.upload(filename, bucket, s3_key)
  34. def upload_seekable(self, manager, filename, bucket, s3_key):
  35. with open(filename, 'rb') as f:
  36. future = manager.upload(f, bucket, s3_key)
  37. future.result()
  38. def upload_nonseekable(self, manager, filename, bucket, s3_key):
  39. with open(filename, 'rb') as f:
  40. future = manager.upload(NonSeekableReader(f), bucket, s3_key)
  41. future.result()
  42. def main():
  43. parser = argparse.ArgumentParser(usage=__doc__)
  44. parser.add_argument('--file-name', required=True, help='The name of file')
  45. parser.add_argument(
  46. '--file-type',
  47. choices=['filename', 'seekable', 'nonseekable'],
  48. required=True,
  49. help='The way to represent the file when uploading',
  50. )
  51. parser.add_argument(
  52. '--s3-bucket',
  53. required=True,
  54. help='The S3 bucket to upload the file to',
  55. )
  56. parser.add_argument('--s3-key', required=True, help='The key to upload to')
  57. parser.add_argument(
  58. '--debug',
  59. action='store_true',
  60. help='Whether to turn debugging on. This will get printed to stderr',
  61. )
  62. args = parser.parse_args()
  63. Uploader().upload(args)
  64. if __name__ == '__main__':
  65. main()