initial commit
This commit is contained in:
66
main.py
Normal file
66
main.py
Normal file
@@ -0,0 +1,66 @@
|
||||
from typing import Any
|
||||
from flask import Flask, json, request
|
||||
from dataclasses import dataclass
|
||||
|
||||
@dataclass
|
||||
class Score:
|
||||
score: int
|
||||
username: str
|
||||
ip: str | None = None
|
||||
|
||||
app = Flask(__name__)
|
||||
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'])
|
||||
def get_score() -> str:
|
||||
return json.dumps(scores)
|
||||
|
||||
|
||||
@app.route('/score', methods = ['POST'])
|
||||
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)
|
||||
return json.dumps({'status': 'success', 'msg': 'created score'})
|
||||
|
||||
if allready_saved_score.ip == score.ip:
|
||||
allready_saved_score.score = score.score
|
||||
return json.dumps({'status': 'updated score'})
|
||||
else:
|
||||
return json.dumps({'status': 'error', 'msg': 'score has been achieved on different machine'})
|
||||
|
||||
def json_body():
|
||||
return request.json
|
||||
|
||||
|
||||
def find_score_by(username: str) -> Score | None:
|
||||
for score in scores:
|
||||
if score.username == username:
|
||||
return score
|
||||
|
||||
return None
|
||||
|
||||
def main():
|
||||
app.run(debug = True)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user