重新启动应用程序后删除添加的数据库记录(heroku/SQLAlchemy) [英] Added database records are deleted after restarting app (heroku/SQLAlchemy)

查看:43
本文介绍了重新启动应用程序后删除添加的数据库记录(heroku/SQLAlchemy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的问题:我创建了一个按预期运行的heroku应用程序,尽管重新启动该应用程序后,该数据库中的所有新记录都被删除了.当我推送到heroku"时,从本地数据库复制的那些文件仍然存在.

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. The ones from my local database that were copied when I "pushed to heroku" are still there.

我是PostgresSQL的新手,但是我仔细地遵循了将代码部署到heroku并设置数据库的说明.这是我的配置的一部分:

I am new to PostgresSQL, but I carefully follewed instructions to deploy my code to heroku and set up the database. 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

我知道最后一行不是如何建立与heroku db的连接(sqlite),尽管我仍然想知道发生了什么.

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.

将数据添加到数据库时,我使用db.session.add(data)和db.session.commit().我像这样创建了一个heroku数据库:

When I add data to my database I use db.session.add(data) and db.session.commit(). I created a heroku database like so:

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

重新启动应用程序后会发生什么?我可能缺少明显的东西.

What happens when the app is restarted? I am probably missing something obvious.

编辑

@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)

谢谢!

推荐答案

两件事-1)使用Heroku在环境中提供的配置连接到PostgreSQL实例.只需使用:

Two things - 1) you connect to your PostgreSQL instance using the configuration that Heroku provides in the environment. Simply use:

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

Heroku将填充环境变量 DATABASE_URL ,并具有连接信息(主机,用户名,密码,数据库).

The environment variable DATABASE_URL will be populated by Heroku, and have the connection information (host, username, password, database).

2)Heroku文件系统是 ephemeral ,并且在dyno重新启动之间不存在.这就是您的 sqlite 数据库消失的原因.

2) The Heroku filesystem is ephemeral, and does not persist between dyno restarts. That is why your sqlite database disappears.

这篇关于重新启动应用程序后删除添加的数据库记录(heroku/SQLAlchemy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆