file_io.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. script_dir = Path(__file__).parent
  11. save_dir = script_dir.joinpath('../save').resolve()
  12. # save_dir = Path('C:\\Projekte\\Python\\Planung\\save')
  13. @app.route('/list/', methods=['GET'])
  14. def list_json():
  15. return json.dumps(list_dict(), indent=2)
  16. def list_dict():
  17. result = {}
  18. for currentFile in save_dir.iterdir():
  19. if currentFile.is_file() and currentFile.name[-5:] == '.json':
  20. name_split = currentFile.name[:-5].split("_")
  21. current_list = result.get(name_split[0], [])
  22. current_list.append(name_split[1])
  23. result[name_split[0]] = current_list
  24. return result
  25. @app.route('/load/<filename>', methods=['GET'])
  26. def load(filename):
  27. full_filename = f'{str(save_dir)}/{filename}.json'
  28. if not Path(full_filename).exists():
  29. file_list = list_dict()
  30. timestamp = file_list[filename][-1]
  31. full_filename = f'{full_filename[:-5]}_{timestamp}.json'
  32. print(full_filename)
  33. return open(full_filename, 'r').read()
  34. @app.route('/save/<filename>', methods=['POST'])
  35. def save(filename):
  36. if request.method != 'POST':
  37. return 'File is missing!'
  38. new_filename = str(save_dir) + '/' + filename + '_' + datetime.now().strftime('%Y%m%d%H%M%S') + '.json'
  39. data = request.get_json()['data']
  40. json.dump(data, open(new_filename, 'w'), indent=2)
  41. print(new_filename)
  42. try:
  43. file_list = list_dict()
  44. timestamp = file_list[filename][-2]
  45. old_filename = str(save_dir) + '/' + filename + "_" + timestamp + '.json'
  46. if old_filename != new_filename and hash(old_filename) == hash(new_filename):
  47. Path(old_filename).unlink()
  48. return 'File saved with no changes!'
  49. except KeyError:
  50. pass
  51. return 'File saved with new data!'
  52. def hash(filename):
  53. BUF_SIZE = 65536
  54. sha1 = hashlib.sha1()
  55. with open(filename, 'rb') as g:
  56. while True:
  57. hashdata = g.read(BUF_SIZE)
  58. if not hashdata:
  59. break
  60. sha1.update(hashdata)
  61. return sha1.hexdigest()
  62. if __name__ == '__main__':
  63. app.run(host='0.0.0.0', port='8082')