implementations.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from pathlib import Path
  2. from flask import request, current_app as app
  3. from flask_json import as_json
  4. from flexmeasures.api.common.responses import (
  5. no_backup,
  6. request_processed,
  7. unrecognized_backup,
  8. )
  9. from flexmeasures.data import db
  10. from flexmeasures.data.scripts.data_gen import (
  11. depopulate_measurements,
  12. depopulate_prognoses,
  13. depopulate_structure,
  14. get_affected_classes,
  15. load_tables,
  16. )
  17. @as_json
  18. def restore_data_response():
  19. delete_structure = True
  20. delete_data = True
  21. restore_structure = True
  22. restore_data = True
  23. try:
  24. backup_name = request.args.get("backup", request.json["backup"])
  25. except KeyError:
  26. return no_backup()
  27. # Make sure backup folder and files exist before restoring
  28. backup_path = app.config.get("FLEXMEASURES_DB_BACKUP_PATH")
  29. if (
  30. not Path("%s/%s" % (backup_path, backup_name)).exists()
  31. or not Path("%s/%s" % (backup_path, backup_name)).is_dir()
  32. ):
  33. return unrecognized_backup()
  34. affected_classes = get_affected_classes(
  35. structure=restore_structure, data=restore_data
  36. )
  37. for c in affected_classes:
  38. file_path = "%s/%s/%s.obj" % (backup_path, backup_name, c.__tablename__)
  39. if not Path(file_path).exists():
  40. return unrecognized_backup(
  41. "Can't load table, because filename %s does not exist."
  42. % c.__tablename__
  43. )
  44. # Reset in play mode only (this endpoint should not have been registered otherwise)
  45. assert app.config.get("FLEXMEASURES_MODE", "") == "play"
  46. if delete_data:
  47. depopulate_prognoses(db)
  48. depopulate_measurements(db)
  49. if delete_structure:
  50. depopulate_structure(db)
  51. # Load backup
  52. load_tables(
  53. db,
  54. backup_name,
  55. structure=restore_structure,
  56. data=restore_data,
  57. backup_path=backup_path,
  58. )
  59. return request_processed("Database restored to %s." % backup_name)