页面加载后Flask DB清空

时间:2014-10-12 01:51:07

标签: python database sqlite flask

我有一个从本地数据库读取的Flask应用程序。由于它没有任何数据,我用我写的add_to_db方法将其播种一次。当我在数据库中检查了一行后,它就有了数据。 但是,当我删除add_to_db行并重新加载页面时,数据库为空。本质上,数据库在页面加载后自行清除。

import sqlite3, datetime
from flask import Flask, request, session, g, redirect, url_for, \
     abort, render_template, flash
from contextlib import closing
# configuration
DATABASE = 'valids.db'
DEBUG = False
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
app = Flask(__name__)
app.config.from_object(__name__)
def connect_db():
    return sqlite3.connect(DATABASE)


def init_db():
    with closing(connect_db()) as db:
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()


def add_to_db(seq):
    g.db.execute("insert into emergencies (sequence, begin) values (?, ?);",(seq,datetime.datetime.now()))


@app.before_request
def before_request():
    g.db = connect_db()


@app.teardown_request
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()


@app.route('/<seq>',methods=['GET'])
def show_entries(seq):
    print(list(g.db.execute('select * from emergencies')))

    add_to_db(seq)
    print(list(g.db.execute('select * from emergencies')))

    statement="select * from emergencies where sequence = '%s';"%seq
    cur = g.db.execute(statement).fetchall()
    if len(cur)>0:
        cur=cur[0]
    else:
        return render_template('notfound.html')
    if cur[3] is None:
        return render_template('house.html')
    else:
        return render_template('notfound.html')


if __name__ == '__main__':
    app.run()

1 个答案:

答案 0 :(得分:0)

您需要提交您的更改:

def add_to_db(seq):
    g.db.execute("insert into emergencies (sequence, begin) values (?, ?);",(seq,datetime.datetime.now()))
    g.db.commit()

或使用connection as a context manager自动提交成功:

def add_to_db(seq):
    with g.db:
        g.db.execute("insert into emergencies (sequence, begin) values (?, ?);",(seq,datetime.datetime.now()))