基本Flask应用程序未在Heroku Postgres数据库中创建表

2024-10-01 22:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我运行heroku日志时--应用程序 我得到了以下错误报告(我只包括了我认为相关的部分,但如果请求,我可以分享其余部分)

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代码按照预期创建了数据库,这可能是正确的吗?如果是这样,我能做些什么来解决这个问题


Tags: fromimportid数据库app应用程序flaskdb
2条回答

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

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

执行这些命令以创建数据库

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

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

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

相关问题 更多 >

    热门问题