download-file 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/env python
  2. """
  3. Downloads a file using s3transfer. You can also chose how type of file that
  4. is downloaded (i.e. filename, seekable, nonseekable).
  5. Usage
  6. =====
  7. NOTE: Make sure you run ``pip install -r requirements-dev.txt`` before running.
  8. To download a file::
  9. ./download-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 NonSeekableWriter:
  16. """A wrapper to hide the ability to seek for a fileobj"""
  17. def __init__(self, fileobj):
  18. self._fileobj = fileobj
  19. def write(self, b):
  20. return self._fileobj.write(b)
  21. class Downloader:
  22. def download(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, 'download_' + file_type)(
  30. manager, args.file_name, args.s3_bucket, args.s3_key
  31. )
  32. def download_filename(self, manager, filename, bucket, s3_key):
  33. manager.download(bucket, s3_key, filename)
  34. def download_seekable(self, manager, filename, bucket, s3_key):
  35. with open(filename, 'wb') as f:
  36. future = manager.download(bucket, s3_key, f)
  37. future.result()
  38. def download_nonseekable(self, manager, filename, bucket, s3_key):
  39. with open(filename, 'wb') as f:
  40. future = manager.download(bucket, s3_key, NonSeekableWriter(f))
  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 downloading',
  50. )
  51. parser.add_argument(
  52. '--s3-bucket',
  53. required=True,
  54. help='The S3 bucket to download the file to',
  55. )
  56. parser.add_argument(
  57. '--s3-key', required=True, help='The key to download to'
  58. )
  59. parser.add_argument(
  60. '--debug',
  61. action='store_true',
  62. help='Whether to turn debugging on. This will get printed to stderr',
  63. )
  64. args = parser.parse_args()
  65. Downloader().download(args)
  66. if __name__ == '__main__':
  67. main()