简体   繁体   English

重新启动应用程序后删除添加的数据库记录(heroku/SQLAlchemy)

[英]Added database records are deleted after restarting app (heroku/SQLAlchemy)

So here's my problem: I created a heroku app that is working as expected, although when the app is restarted, all the new records in the database are deleted.所以这是我的问题:我创建了一个按预期工作的 heroku 应用程序,尽管当应用程序重新启动时,数据库中的所有新记录都会被删除。 The ones from my local database that were copied when I "pushed to heroku" are still there.当我“推送到heroku”时复制的本地数据库中的那些仍然存在。

I am new to PostgresSQL, but I carefully follewed instructions to deploy my code to heroku and set up the database.我是 PostgresSQL 的新手,但我仔细按照说明将我的代码部署到 heroku 并设置了数据库。 Here's part of my configuration:这是我的配置的一部分:

# defines the full path for the database
DATABASE_PATH = os.path.join(basedir, DATABASE)
# the database uri
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH

I know that last line is not how a connection with a heroku db should be established (sqlite), though I'd still like to know what is happening.我知道最后一行不是应该如何建立与 heroku db 的连接(sqlite),尽管我仍然想知道发生了什么。

When I add data to my database I use db.session.add(data) and db.session.commit().当我将数据添加到我的数据库时,我使用 db.session.add(data) 和 db.session.commit()。 I created a heroku database like so:我创建了一个 heroku 数据库,如下所示:

$ heroku addons:create heroku-postgresql:hobby-dev

What happens when the app is restarted?重新启动应用程序时会发生什么? I am probably missing something obvious.我可能遗漏了一些明显的东西。

EDIT编辑

@admin_blueprint.route('/modify/add-post/',methods=['GET', 'POST'])
@login_required
def add_post():
    error = None
    form = AddPostForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            now=datetime.datetime.now()  
            poster=session['adminname']
            new_post = Post(form.text.data,poster, now,form.add_file.data)
            db.session.add(new_post)
            db.session.commit()

            return redirect(url_for('home.posts'))
        else: 
            return render_template("adm_posts.html",error=error,form=form)

    if request.method == 'GET':
        return render_template("adm_posts.html",form=form)

Thanks!谢谢!

Two things - 1) you connect to your PostgreSQL instance using the configuration that Heroku provides in the environment.两件事 - 1)您使用 Heroku 在环境中提供的配置连接到 PostgreSQL 实例。 Simply use:只需使用:

import os
SQL_ALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']

The environment variable DATABASE_URL will be populated by Heroku, and have the connection information (host, username, password, database).环境变量DATABASE_URL将由 Heroku 填充,并具有连接信息(主机、用户名、密码、数据库)。

2) The Heroku filesystem is ephemeral , and does not persist between dyno restarts. 2) Heroku 文件系统是短暂的,并且不会在 dyno 重新启动之间持续存在。 That is why your sqlite database disappears.这就是您的sqlite数据库消失的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM