from typing import Any, Dict from flask import Flask, json, request from dataclasses import dataclass from flask_cors import CORS, cross_origin @dataclass class Score: score: int username: str ip: str | None = None @dataclass() class ScoreDTO: score: int username: str app = Flask(__name__) cors = CORS(app) scores: list[Score] = [] @app.route('/') def root(): return 'This is the snakes backend for the leaderboard and should only be requested by the snakes webapp' @app.route('/score', methods = ['GET']) @cross_origin() def get_score() -> str: scoreDTOs: list[ScoreDTO] = list(map(lambda score: ScoreDTO(score.score, score.username), scores)) scoreDTOs.sort(reverse = True, key = lambda score: score.score) return json.dumps(scoreDTOs) @app.route('/score', methods = ['POST']) @cross_origin() def add_score() -> str: body: Any | None = request.json if body is None: return json.dumps({'status': 'error', 'msg': 'could not parse passed json'}) score: Score = Score(**body) ip = request.remote_addr if ip is None: return json.dumps({'status': 'error', "msg": 'not allowed. Ip of sender required'}) score.ip = ip allready_saved_score = find_score_by(score.username) print(allready_saved_score) if allready_saved_score is None: scores.append(score) writeScores() return json.dumps({'status': 'success', 'msg': 'created score'}) if allready_saved_score.ip == score.ip: if score.score > allready_saved_score.score: allready_saved_score.score = score.score writeScores() return json.dumps({'status': 'success', 'msg': 'updated score'}) else: return json.dumps({'status': 'success', 'msg': 'score is not better. no update'}) else: return json.dumps({'status': 'error', 'msg': 'score has been achieved on different machine'}) def json_body(): return request.json def writeScores(): f = open('scores.json', 'w') f.write(json.dumps(scores)) def find_score_by(username: str) -> Score | None: for score in scores: if score.username == username: return score return None def main(): f = open('scores.json', 'r') scoresDictionary: list[Dict[str, Any]] = json.loads(f.read()) for scoreObject in scoresDictionary: scores.append(Score(**scoreObject)) app.run(debug = True) if __name__ == "__main__": main()