1

I am struggling to render my PostgreSQL data in my flask app and I am not sure why. The GET route I am attempting to render all of the data with is returning an empty array, even though my data table has 16 records in it (I premade this database/table in PSQL). I don't think I am truly connected to my PSQL, but am at a loss for how to resolve this. Here is the result in the browser/CURL: screenshot.

Here is my code so far:

app.py:

from flask import Flask, jsonify
from flask_cors import CORS
import models
from flask_login import LoginManager
from resources.authors import authors

DEBUG = True
PORT = 8000

login_manager = LoginManager()

app = Flask(__name__)
app.secret_key = ''

login_manager.init_app(app)

# CORS arguments go here


# Register blueprints with the app
app.register_blueprint(authors, url_prefix='/api/v1/authors')




if __name__ == '__main__':
    models.initialize()
    app.run(debug=DEBUG, port=PORT)

models.py:

from peewee import *
from flask_login import UserMixin
from flask_bcrypt import generate_password_hash
import datetime

# connecting to my psql database
DATABASE = PostgresqlDatabase('quoticus')


# Author model
class Author(Model):
    name = CharField()
    quote = TextField()
    source = CharField(max_length=255)
    date = CharField()

    class Meta:
        database = DATABASE

resources/authors.py

from models import Author
from flask import Blueprint, jsonify

from playhouse.shortcuts import model_to_dict


# Blueprint
authors = Blueprint('authors', 'authors')

# Route
@authors.route('/', methods=["GET"])
def get_authors():
    authors = Author.select()
    for author in authors:
        print(model_to_dict(author))
    author_dict = [model_to_dict(author)for author in authors]
    return jsonify({
        'data': author_dict,
        'message': f"Successfully found {len(author_dict)} authors",
        'status': 200
        }), 200

Any help is appreciated!

I have tried various DATABASE connections to the Postgresql Database with the exact same result. Even if I add username, port, etc.

I have also tried altering the route URL to no avail.

joeljpa
  • 317
  • 2
  • 13
SirJamesG
  • 11
  • 3
  • Can you share some kind of proof or otherwise that the data in fact exists in Postgres? If the table did not exist, then iterating over the `select()` query would raise an exception - so it looks like your table does indeed exist, but is empty. – coleifer May 27 '23 at 20:21

1 Answers1

0

I was able to connect, I was missing 1 designation in my schema:

    # Author model
class Author(Model):
    name = CharField()
    quote = TextField()
    source = CharField(max_length=255)
    date = CharField()

    class Meta:
        database = DATABASE
        *** table_name = 'authors' ***

Otherwise It was searching the first table in the database which was 'author' (my schema, i believe?).

Im rolling now. Hope this helps someone in the future!

SirJamesG
  • 11
  • 3