Basic Flask 应用程序未在 Heroku Postgres 数据库中创建 Table

Basic Flask App Not Creating Table in Heroku Postgres Database

我有一个非常基本的 Flask 应用程序,其中包含我正在制作的 postgres 数据库以及教程。它在本地工作,我已将它部署到 heroku,但是当我尝试 运行 应用程序时,我收到内部服务器错误。

当我 运行 heroku logs --app 我收到以下错误报告(我只包含了我认为相关的部分,但如果需要,我可以分享其余部分)

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "favquotes" does not exist
2021-07-19T17:56:57.596569+00:00 app[web.1]: LINE 2: FROM favquotes
2021-07-19T17:56:57.596570+00:00 app[web.1]: ^
2021-07-19T17:56:57.596570+00:00 app[web.1]:
2021-07-19T17:56:57.596570+00:00 app[web.1]: [SQL: SELECT favquotes.id AS favquotes_id, favquotes.author AS favquotes_author, favquotes.quote AS favquotes_quote
2021-07-19T17:56:57.596571+00:00 app[web.1]: FROM favquotes]
2021-07-19T17:56:57.596571+00:00 app[web.1]: (Background on this error at: https://sqlalche.me/e/14/f405)

经过一些研究,我发现我可以使用 heroku 上的 Dataclips 仪表板检查我的数据库。当我在那里查看时,我看到在 Schema Explorer 下我收到一条消息:

No columns or tables found

此时我相信,但可能是错误的,我的 python 主文件没有按预期创建数据库。即使它确实可以在我的本地机器上创建一个 postgres 数据库。我的主py文件内容如下:

from flask import Flask , render_template , request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
import os



app = Flask(__name__)

load_dotenv()

app.config['PROPAGATE_EXCEPTIONS'] = True
app.config['SQLALCHEMY_DATABASE_URI']=os.environ.get('SQL_URI')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False


db=SQLAlchemy(app)

class Favquotes(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author = db.Column(db.String(30))
    quote= db.Column(db.String(2000))

@app.route('/')
def index():
    result = Favquotes.query.all()
    return render_template('index.html', result=result)



@app.route('/quotes')
def quotes():
    return render_template('quotes.html')


@app.route('/process', methods = ['POST'])
def process():
    author = request.form['author']
    quote = request.form['quote']
    quotedata = Favquotes(author=author, quote=quote)
    db.session.add(quotedata)
    db.session.commit()
    return redirect(url_for('index'))

我的 python 代码是否按预期创建了数据库?如果是这样,我该怎么做才能解决这个问题?

经过一番搜索,我找到了这个解决方案。我可以将以下行添加到我的 python 代码中以在 heroku 中创建我的 table。

with app.app_context():
    db.create_all()

您也可以使用终端执行这些命令。

在 heroku 中点击更多按钮(右上角)。转到 运行 控制台并键入 python。这将打开 python 终端。

执行这些命令来创建数据库。

from main import app,db
with app.app_context():
    db.create_all()