python-3.x 为什么我在Flask中渲染PostgreSQL数据时得到一个空数组响应?

ss2ws0br  于 2023-05-30  发布在  Python
关注(0)|答案(1)|浏览(165)

我正在努力在我的flask应用程序中呈现我的PostgreSQL数据,我不知道为什么。我试图呈现所有数据的GET路由返回一个空数组,即使我的数据表中有16条记录(我在PSQL中预先创建了这个数据库/表)。我不认为我真的连接到我的PSQL,但我在如何解决这个问题的损失。下面是browser/CURL中的结果:screenshot
以下是我目前为止的代码:

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

资源/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

任何帮助是赞赏!
我已经尝试了各种数据库连接到PostgreSQL数据库与完全相同的结果。即使我添加用户名、端口等
我也试过改变路线的网址无济于事。

fae0ux8s

fae0ux8s1#

我能够连接,我在我的架构中缺少1个指定:

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

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

否则,它将搜索数据库中的第一个表,即“作者”(我的模式,我相信?)).
我现在就在拍。希望这对将来的人有帮助!

相关问题