website_11.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. def synchronize(self, delete=False):
  2. """Synchronize the localpath to S3.
  3. Upload new or changed files.
  4. Delete files that no longer exist locally."""
  5. bucket = self.get_bucket()
  6. s3_paths = s3_util.get_paths_from_keys(bucket)
  7. local_files = set()
  8. for dirpath, dirnames, filenames in os.walk(self.localpath):
  9. for filename in filenames:
  10. file_path = os.path.join(dirpath,filename)
  11. file_key = os.path.relpath(file_path,self.localpath)
  12. if os.sep == "\\":
  13. #Windows paths need conversion
  14. file_key = file_key.replace("\\","/")
  15. local_files.add(file_key)
  16. try:
  17. s3_key = s3_paths[file_key]
  18. except KeyError:
  19. #File is new
  20. s3_key = bucket.new_key(file_key)
  21. logger.info("Uploading new file: {0}".format(file_key))
  22. s3_key.set_contents_from_filename(file_path)
  23. s3_key.set_acl("public-read")
  24. else:
  25. #File already exists, check if it's changed.
  26. local_md5 = util.md5_for_file(file_path)
  27. if local_md5 != s3_key.etag.replace("\"",""):
  28. #File has changed
  29. logger.info("Uploading changed file: {0}".format(file_key))
  30. s3_key.set_contents_from_filename(file_path)
  31. s3_key.set_acl("public-read")
  32. if delete:
  33. #Delete all files that don't exist locally
  34. for name, key in s3_paths.items():
  35. if name not in local_files:
  36. #Delete it.
  37. logger.info("Deleting old file: {0}".format(name))
  38. key.delete()