file-io.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from pathlib import Path
  2. from flask import request, Flask
  3. import json
  4. from flask_cors import CORS
  5. from datetime import datetime
  6. import hashlib
  7. app = Flask(__name__)
  8. # cors = CORS(app, resources={r"/*": {"origins": "http://localhost:4200/"}})
  9. CORS(app)
  10. currentDirectory = Path('C:\\Projekte\\Python\\Planung\\save')
  11. @app.route('/list/', methods=['GET'])
  12. def list_json():
  13. return json.dumps(list_dict(), indent=2)
  14. def list_dict():
  15. result = {}
  16. for currentFile in currentDirectory.iterdir():
  17. if currentFile.is_file() and currentFile.name[-5:] == '.json':
  18. name_split = currentFile.name[:-5].split("_")
  19. current_list = result.get(name_split[0], [])
  20. current_list.append(name_split[1])
  21. result[name_split[0]] = current_list
  22. return result
  23. @app.route('/load/<filename>', methods=['GET'])
  24. def load(filename):
  25. full_filename = f'{str(currentDirectory)}/{filename}.json'
  26. if not Path(full_filename).exists():
  27. file_list = list_dict()
  28. timestamp = file_list[filename][-1]
  29. full_filename = f'{full_filename[:-5]}_{timestamp}.json'
  30. print(full_filename)
  31. return open(full_filename, 'r').read()
  32. @app.route('/save/<filename>', methods=['POST'])
  33. def save(filename):
  34. if request.method != 'POST':
  35. return 'File is missing!'
  36. new_filename = str(currentDirectory) + '/' + filename + '_' + datetime.now().strftime('%Y%m%d%H%M%S') + '.json'
  37. data = request.get_json()['data']
  38. json.dump(data, open(new_filename, 'w'), indent=2)
  39. print(new_filename)
  40. try:
  41. file_list = list_dict()
  42. timestamp = file_list[filename][-2]
  43. old_filename = str(currentDirectory) + '/' + filename + "_" + timestamp + '.json'
  44. if old_filename != new_filename and hash(old_filename) == hash(new_filename):
  45. Path(old_filename).unlink()
  46. return 'File saved with no changes!'
  47. except KeyError:
  48. pass
  49. return 'File saved with new data!'
  50. def hash(filename):
  51. BUF_SIZE = 65536
  52. sha1 = hashlib.sha1()
  53. with open(filename, 'rb') as g:
  54. while True:
  55. hashdata = g.read(BUF_SIZE)
  56. if not hashdata:
  57. break
  58. sha1.update(hashdata)
  59. return sha1.hexdigest()