amazon-s3-upload-static-site.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python
  2. # Author: Nicholas Kuechler
  3. # URL: http://nicholaskuechler.com
  4. # Github: https://github.com/nicholaskuechler
  5. import argparse
  6. import boto3
  7. import mimetypes
  8. import os
  9. import sys
  10. from boto3.s3.transfer import S3Transfer
  11. VERBOSE = False
  12. DEFAULT_REGION = "us-west-2"
  13. def main(args):
  14. bucket = args.bucket
  15. upload_dir = args.dir
  16. print("Uploading directory: %s" % (upload_dir))
  17. print("Uploading to bucket: %s" % (bucket))
  18. s3_client = boto3.client('s3', DEFAULT_REGION)
  19. transfer = S3Transfer(s3_client)
  20. for root, dirs, files in os.walk(upload_dir):
  21. for name in files:
  22. path = root.split(os.path.sep)[1:]
  23. path.append(name)
  24. key_id = os.path.join(*path)
  25. upload_file = os.path.join(root, name)
  26. if key_id == sys.argv[0]:
  27. if VERBOSE:
  28. print("Skipping upload of this uploader script")
  29. continue
  30. mime_type = mimetypes.guess_type(upload_file)[0]
  31. # print "mime_type: %s" % (mime_type)
  32. if mime_type:
  33. content_type = {'ContentType': mime_type}
  34. else:
  35. mime_type = "text/html"
  36. # upload normal files
  37. if VERBOSE:
  38. print("Uploading file: %s to %s:%s type: %s"
  39. % (upload_file, bucket, key_id, mime_type))
  40. transfer.upload_file(upload_file, bucket, key_id,
  41. extra_args=content_type)
  42. # for .html files, excluding index.html, also upload the file
  43. # without .html extension for pretty urls
  44. if (upload_file.endswith('.html') and not
  45. upload_file.endswith('index.html')):
  46. key_id_pretty_url = key_id.replace('.html', '')
  47. if VERBOSE:
  48. print("Uploading file WITHOUT HTML EXTENSION: "
  49. "%s to %s:%s type: %s"
  50. % (upload_file, bucket, key_id_pretty_url,
  51. mime_type))
  52. transfer.upload_file(upload_file, bucket, key_id_pretty_url,
  53. extra_args=content_type)
  54. print("Upload completed.")
  55. if __name__ == "__main__":
  56. parser = argparse.ArgumentParser()
  57. parser.add_argument('-d', '--dir',
  58. type=str,
  59. required=False,
  60. default="_site",
  61. help='Directory to upload. Defaults to _site in the '
  62. 'current working directory.')
  63. parser.add_argument('-b', '--bucket',
  64. type=str,
  65. required=True,
  66. help='S3 Bucket')
  67. parser.add_argument("-v", "--verbose", action="store_true",
  68. default=False,
  69. help="Increase output verbosity")
  70. args = parser.parse_args()
  71. VERBOSE = args.verbose
  72. main(args)