From 5af581923d0d1e8d130553438696906e70dd3381 Mon Sep 17 00:00:00 2001 From: Jack Jackson Date: Tue, 23 Jan 2024 22:16:10 -0800 Subject: [PATCH] Can return HTML content for a player --- NOTES.md | 1 + app/main.py | 17 ++++++++++++++++- app/models.py | 2 +- app/templates/player_detail.html | 11 +++++++++++ 4 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 app/templates/player_detail.html diff --git a/NOTES.md b/NOTES.md index 42ec51a..0298bce 100644 --- a/NOTES.md +++ b/NOTES.md @@ -3,6 +3,7 @@ - [X] Basic Game Definition - [X] Basic Player Definition - [ ] Basic Deck Definition +- [X] Figure out how to return JSON or html (`render_template`) - [ ] Basic testing - [ ] Swagger API - [ ] Local development tool to clear/seed database diff --git a/app/main.py b/app/main.py index 7965301..fb51730 100644 --- a/app/main.py +++ b/app/main.py @@ -1,4 +1,4 @@ -from flask import Blueprint, request +from flask import Blueprint, render_template, request from . import db from .models import Deck, Game, Player @@ -18,5 +18,20 @@ def create_player(): db.session.commit() return {'id': player.id} +@main.route("/player/") +def get_player(player_id: str): + player_data = _jsonify(db.session.get(Player, int(player_id))) + content_type = request.headers.get('Content-Type') + if content_type == 'application/json': + return player_data + else: # Assume they want HTML + return render_template('player_detail.html', **player_data) + # TODO - implement a GET method - can it be a separate method, or must it be the same annotation with an `if method==`? # Time for testing, methinks! + +# TODO - would this be better as a method on a class extending `db.Model` that the classes in `models.py` could then +# extend? +# (Probably not, as we'd still need to explicitly call it - it wouldn't be implicitly called _by_ Flask) +def _jsonify(o): + return {k: v for (k, v) in o.__dict__.items() if k is not '_sa_instance_state'} \ No newline at end of file diff --git a/app/models.py b/app/models.py index 63960d4..80de9f4 100644 --- a/app/models.py +++ b/app/models.py @@ -11,7 +11,7 @@ class Deck(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), nullable=False) description = db.Column(db.String) - owner = db.Column(db.String, db.ForeignKey(Player.__table__.c.id), nullable=False, ) + owner = db.Column(db.String, db.ForeignKey(Player.__table__.c.id), nullable=False) class Game(db.Model): id = db.Column(db.Integer, primary_key=True) diff --git a/app/templates/player_detail.html b/app/templates/player_detail.html new file mode 100644 index 0000000..6c51db0 --- /dev/null +++ b/app/templates/player_detail.html @@ -0,0 +1,11 @@ + + + + + Player - {{ name }} + + +

Hello World!

+

This is the page for player {{ name }} who has id {{ id }}

+ + \ No newline at end of file