file_io.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # import os
  2. from pathlib import Path
  3. from flask import Blueprint, Response, request
  4. from flask_cors import CORS
  5. from datetime import datetime
  6. import json
  7. import hashlib
  8. # import time
  9. from webservice.auth import Auth
  10. from webservice.planner_load import PlannerLoad
  11. from webservice.config_load import ConfigLoad
  12. bp = Blueprint("file_io", __name__)
  13. # cors = CORS(app, resources={r"/*": {"origins": "http://localhost:4200/"}})
  14. CORS(bp)
  15. script_dir = Path(__file__).parent
  16. save_dir = script_dir.parent.joinpath("save")
  17. planner_dir = script_dir.parent.joinpath("export")
  18. config_dir = script_dir.parent.joinpath("config")
  19. # save_dir = Path('C:\\Projekte\\Python\\Planung\\save')
  20. user_info = None
  21. timestamp_keywords = ("accounts", "plan", "marketing")
  22. @bp.route("/login/", methods=["POST"])
  23. def login():
  24. user = request.get_json()["data"]["user"]
  25. password = request.get_json()["data"]["password"]
  26. user_info = Auth().get_user(user, password)
  27. return Response(response=json.dumps(user_info), mimetype="application/json")
  28. @bp.route("/list", methods=["GET"])
  29. def list_json():
  30. return json.dumps(list_dict(), indent=2)
  31. def list_dict():
  32. result = {"list": [], "tree": {}}
  33. for currentFile in save_dir.iterdir():
  34. if currentFile.is_file() and currentFile.name[-5:] == ".json":
  35. year, version, timestamp = currentFile.name[:-5].split("_")
  36. if year not in result["tree"]:
  37. result["tree"][year] = {}
  38. if version not in result["tree"][year]:
  39. result["tree"][year][version] = []
  40. result["tree"][year][version].append(timestamp)
  41. result["list"].append({"year": year, "version": version, "timestamp": timestamp})
  42. result["list"].sort(key=lambda x: x["timestamp"])
  43. return result
  44. @bp.route("/load/<year>/<version>/<timestamp>", methods=["GET"])
  45. def load(year, version, timestamp):
  46. file = full_filename(year, version, timestamp)
  47. if timestamp == "new":
  48. return Response(response=new_file(year), mimetype="application/json")
  49. if timestamp == "current" or not Path(file).exists():
  50. file_list = list_dict()
  51. timestamp2 = file_list["tree"][year][version][-1]
  52. file = full_filename(year, version, timestamp2)
  53. print(file)
  54. with open(file, "r") as frh:
  55. structure = json.loads(frh.read())
  56. if "options" not in structure[0]:
  57. p_load = PlannerLoad(planner_dir)
  58. structure = p_load.convert_file(structure)
  59. elif timestamp in timestamp_keywords:
  60. p_load = PlannerLoad(planner_dir)
  61. p_load.load_values(year)
  62. p_load.set_structure(structure)
  63. structure = p_load.update_values(timestamp)
  64. return Response(response=json.dumps(structure), mimetype="application/json")
  65. def full_filename(year, version, timestamp):
  66. return f"{str(save_dir)}/{year}_{version}_{timestamp}.json"
  67. @bp.route("/new/<year>", methods=["GET"])
  68. def new_file(year):
  69. p_load = PlannerLoad(planner_dir)
  70. structure = p_load.new_file(year)
  71. return json.dumps(structure)
  72. @bp.route("/load/<filename>", methods=["GET"])
  73. def load_file(filename):
  74. full_filename = f"{str(save_dir)}/{filename}.json"
  75. if not Path(full_filename).exists():
  76. file_list = list_dict()
  77. timestamp = file_list[filename][-1]
  78. full_filename = f"{full_filename[:-5]}_{timestamp}.json"
  79. print(full_filename)
  80. with open(full_filename, "r") as frh:
  81. return frh.read()
  82. @bp.route("/save/<year>/<version>", methods=["POST"])
  83. def save_version(year, version):
  84. return save(year + "_" + version)
  85. @bp.route("/save/<filename>", methods=["POST"])
  86. def save(filename):
  87. if request.method != "POST":
  88. return "File is missing!"
  89. new_filename = str(save_dir) + "/" + filename + "_" + datetime.now().strftime("%Y%m%d%H%M%S") + ".json"
  90. data = request.get_json()["data"]
  91. with open(new_filename, "w") as fwh:
  92. json.dump(data, fwh, indent=2)
  93. print(new_filename)
  94. try:
  95. file_list = list_dict()
  96. timestamp = file_list[filename][-2]
  97. old_filename = str(save_dir) + "/" + filename + "_" + timestamp + ".json"
  98. if old_filename != new_filename and hash(old_filename) == hash(new_filename):
  99. Path(old_filename).unlink()
  100. return "File saved with no changes!"
  101. except KeyError:
  102. pass
  103. return "File saved with new data!"
  104. @bp.route("/config", methods=["GET"])
  105. def config():
  106. cfg = ConfigLoad(str(config_dir))
  107. return Response(response=json.dumps(cfg.load_file("reisacher", "2023")), mimetype="application/json")
  108. @bp.route("/accounts/<period>", methods=["GET"])
  109. def accounts(period):
  110. with open(planner_dir.joinpath(f"accounts_{period}.json"), "r") as frh:
  111. return frh.read()
  112. def hash(filename):
  113. BUF_SIZE = 65536
  114. sha1 = hashlib.sha1()
  115. with open(filename, "rb") as g:
  116. while True:
  117. hashdata = g.read(BUF_SIZE)
  118. if not hashdata:
  119. break
  120. sha1.update(hashdata)
  121. return sha1.hexdigest()