file_io.py 4.7 KB

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