Skip to content

Instantly share code, notes, and snippets.

@DefProc
Last active June 26, 2023 18:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DefProc/7448951e79bfd7ade3c3e0c77245aa99 to your computer and use it in GitHub Desktop.
Save DefProc/7448951e79bfd7ade3c3e0c77245aa99 to your computer and use it in GitHub Desktop.
get top games
"""
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
@DefProc
Copy link
Author

DefProc commented May 17, 2017

restrict to the last 48 hours by changing line 41 to:

games = Game.query.order_by(Game.score.desc()).filter(Game.timestamp > datetime.datetime.utcnow() - datetime.timedelta(hours=48)).limit(count).all()

?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment