Last active
June 26, 2023 18:57
-
-
Save DefProc/7448951e79bfd7ade3c3e0c77245aa99 to your computer and use it in GitHub Desktop.
get top games
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This module provides the application programming interface for the | |
scoreboard application. | |
""" | |
from aniso8601 import parse_datetime | |
from flask import jsonify, request | |
from scoreboard import app, db | |
from scoreboard.models import Game | |
@app.route("/api/create", methods=["POST"]) | |
def create(): | |
""" | |
Create a record of a game. | |
""" | |
# Extract and validate the document. | |
document = request.get_json() | |
# Build a game record and store it in the database. | |
game = Game( | |
timestamp=parse_datetime(document["timestamp"]), | |
name=document["name"], | |
twitter=document.get("twitter", None), | |
score=document["score"] | |
) | |
db.session.add(game) | |
db.session.commit() | |
# If we made it this far, the operation was successful. | |
return "", 200 | |
@app.route("/api/top", methods=["GET"]) | |
def top(): | |
""" | |
Return a document containing a list of the top games. | |
:param count: the number of games to return. | |
""" | |
# Extract parameters. | |
count = int(request.args.get("count", "10")) | |
# Query the database and format the result. | |
games = Game.query.order_by(Game.score.desc()).limit(count).all() | |
return jsonify(to_serialisable(games)) | |
@app.route("/api/recent", methods=["GET"]) | |
def recent(): | |
""" | |
Return a document containing a list of the most recent games. | |
:param count: the number of games to return. | |
""" | |
# Extract parameters. | |
count = int(request.args.get("count", "10")) | |
# Query the database and format the result. | |
games = Game.query.order_by(Game.timestamp.desc()).limit(count).all() | |
return jsonify(to_serialisable(games)) | |
def to_serialisable(games): | |
""" | |
Return a serialisable collection of games from a result set. | |
:param games: result set of games. | |
""" | |
output = [] | |
for game in games: | |
output.append({ | |
"id": game.id, | |
"timestamp": game.timestamp.isoformat(), | |
"name": game.name, | |
"twitter": game.twitter, | |
"score": game.score | |
}) | |
return output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
restrict to the last 48 hours by changing line 41 to:
?