-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathgames.py
More file actions
41 lines (32 loc) · 1.25 KB
/
games.py
File metadata and controls
41 lines (32 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from flask import jsonify, Response, Blueprint
from models import db, Game, Publisher, Category
from sqlalchemy.orm import Query
# Create a Blueprint for games routes
games_bp = Blueprint('games', __name__)
def get_games_base_query() -> Query:
return db.session.query(Game).join(
Publisher,
Game.publisher_id == Publisher.id,
isouter=True
).join(
Category,
Game.category_id == Category.id,
isouter=True
)
@games_bp.route('/api/games', methods=['GET'])
def get_games() -> Response:
# Use the base query for all games
games_query = get_games_base_query().all()
# Convert the results using the model's to_dict method
games_list = [game.to_dict() for game in games_query]
return jsonify(games_list)
@games_bp.route('/api/games/<int:id>', methods=['GET'])
def get_game(id: int) -> tuple[Response, int] | Response:
# Use the base query and add filter for specific game
game_query = get_games_base_query().filter(Game.id == id).first()
# Return 404 if game not found
if not game_query:
return jsonify({"error": "Game not found"}), 404
# Convert the result using the model's to_dict method
game = game_query.to_dict()
return jsonify(game)