file_backup.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import hashlib
  2. import os
  3. import shutil
  4. from datetime import datetime
  5. from pathlib import Path
  6. def gcstruct_backup(base_dir: str) -> None:
  7. print("Sicherung fuer GCStruct")
  8. for f in Path(base_dir).rglob("Kontenrahmen.csv"):
  9. if f.parent.name == "Kontenrahmen":
  10. print("* " + str(f))
  11. copy_file_with_timestamp(str(f), str(f.parent / "Backup"))
  12. def copy_file_with_timestamp(file_path: str, backup_folder: str) -> None:
  13. """
  14. Copies a file to a backup folder with a timestamp in the filename
  15. only if the file has changed since last run.
  16. """
  17. if not Path(backup_folder).exists():
  18. os.makedirs(backup_folder, exist_ok=True)
  19. file_mod_timestamp = datetime.fromtimestamp(Path(file_path).stat().st_mtime).strftime("%Y%m%d_%H%M%S")
  20. file_extension = Path(file_path).suffix
  21. file_basename = Path(file_path).stem
  22. backup_filename = f"{file_basename}__{file_mod_timestamp}{file_extension}"
  23. if Path(backup_folder + "\\" + backup_filename).exists():
  24. # backup folder is already up-to-date
  25. return
  26. latest_file = get_file_with_latest_timestamp(backup_folder, file_basename + "__")
  27. if latest_file != "" and hash(file_path) == hash(latest_file):
  28. # different timestamp, but same content. Keep old timestamp and backup file.
  29. return
  30. shutil.copy2(file_path, backup_folder + "\\" + backup_filename)
  31. return
  32. def get_file_with_latest_timestamp(folder_path: str, filename_pattern: str) -> str:
  33. """
  34. Gets the latest timestamp from files in a folder with a matching filename.
  35. """
  36. files = [str(f) for f in Path(folder_path).iterdir() if f.name.startswith(filename_pattern)]
  37. if len(files) == 0:
  38. return ""
  39. files.sort()
  40. return files[-1]
  41. def hash(filename: str) -> str:
  42. with open(filename, "rb") as frh:
  43. return hashlib.sha256(frh.read()).hexdigest()
  44. def main() -> None:
  45. gcstruct_backup("C:\\GlobalCube_Entwicklung")
  46. def copy_deployment(server_folder: str, backup_folder: str):
  47. filename = "GC_BACKUP_CONTENT_STORE_DAILY.zip"
  48. source_file = Path(server_folder + "\\deployment\\" + filename)
  49. if not source_file.exists():
  50. print(f"!! Datei {filename} existiert nicht !!")
  51. return
  52. file_ts = source_file.stat().st_mtime
  53. print(filename + " - " + datetime.fromtimestamp(file_ts).strftime("%d.%m.%Y %H:%M:%S"))
  54. if file_ts < datetime.now().timestamp() - 3 * 24 * 60 * 60:
  55. print(f"!! Datei {filename} ist aelter als 3 Tage !!")
  56. return
  57. if not Path(backup_folder).exists():
  58. os.makedirs(backup_folder, exist_ok=True)
  59. dest_file = Path(f"{backup_folder}\\{filename}")
  60. if dest_file.exists() and file_ts == dest_file.stat().st_mtime:
  61. print(f"Datei {filename} ist bereits up-to-date.")
  62. return
  63. shutil.copy2(source_file, dest_file)
  64. if __name__ == "__main__":
  65. main()