1. import time
  2. import hashlib
  3. import json
  4. import sys
  5. from typing import Dict, Any
  6. class FormChangeMonitor:
  7. def __init__(self, form_data: Dict[str, Any], interval: int = 1):
  8. """
  9. Initializes the FormChangeMonitor.
  10. Args:
  11. form_data: The initial state of the form.
  12. interval: The interval (in seconds) to check for changes.
  13. """
  14. self.form_data = form_data
  15. self.interval = interval
  16. self.previous_hash = self._calculate_hash(form_data)
  17. def _calculate_hash(self, data: Dict[str, Any]) -> str:
  18. """Calculates a hash of the form data."""
  19. data_string = json.dumps(data, sort_keys=True).encode('utf-8')
  20. return hashlib.sha256(data_string).hexdigest()
  21. def check_changes(self) -> Dict[str, Any]:
  22. """
  23. Checks for changes in the form data.
  24. Returns:
  25. The updated form data if changes are detected, otherwise None.
  26. """
  27. try:
  28. current_data = self.form_data # Get the current form data
  29. current_hash = self._calculate_hash(current_data)
  30. if current_hash != self.previous_hash:
  31. self.previous_hash = current_hash
  32. print("Form data changed!")
  33. return current_data
  34. else:
  35. return None # No changes
  36. except Exception as e:
  37. print(f"Error during change check: {e}")
  38. return None
  39. def run(self):
  40. """Runs the monitoring loop."""
  41. while True:
  42. updated_data = self.check_changes()
  43. if updated_data:
  44. self.form_data = updated_data # Update the form data
  45. print("Updated form data:", updated_data)
  46. time.sleep(self.interval)
  47. if __name__ == '__main__':
  48. # Example usage:
  49. initial_form_data = {"name": "Alice", "age": 30, "city": "New York"}
  50. monitor = FormChangeMonitor(initial_form_data, interval=2)
  51. monitor.run()

Add your comment