Ziyuan Ma Ziyuan Ma - 1 month ago 13
Python Question

OperationalError: no such table: entries while "init_db()" already inserted in flaskr.py

Here is a part of my flaskr.py,
I tried to run it on 127.0.0.1:5000 but it gave me a Internal Error.
Then I checked the error_log, which telled,

File "/var/www/html/flaskr/flaskr.py", line 66, in show_entries (model,sn,user,status))
OperationalError: no such table: entries "


Here are my codes:

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

def init_db():
"""Creates the database."""
with app.app_context():
db = get_db()
with app.open_resource('/var/www/html/flaskr/schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()


def get_db():
"""
Opens a new database connection if there is none yet for the
current application context.
"""
top = _app_ctx_stack.top
if not hasattr(top, 'sqlite_db'):
sqlite_db = sqlite3.connect(app.config['DATABASE'])
sqlite_db.row_factory = sqlite3.Row
top.sqlite_db = sqlite_db
return top.sqlite_db

@app.route('/')
def show_entries():
db = get_db()
with open('/var/www/html/flaskr/hardwarelist.txt') as fl:
for eachline in fl:
(model,sn,user,status)=eachline.strip().split(',')
db.execute('insert into entries (model,sn,user,status) values (?, ?, ?, ?)',(model,sn,user,status))
fl.close()
cur = db.execute('select model,sn,status,user from entries order by id desc')
entries = cur.fetchall()
return render_template('show_entries.html', entries=entries)

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


I thought the error caused from my "init_db" function did not run well ,so I can't get the table of entries.
But here were no error report about init_db , what should I do to figure out this question & fix it?

Update:
There is my schema.sql:

drop table if exists entries;
create table entries (
id integer primary key autoincrement,
model text not null,
sn text not null,
status text not null,
user text not null
);

Answer

I happened to solve the problem by deleting these two lines.

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

and remain:

init_db()

Then everything run perfectly.However don't know how it caused..... Answered it just for note & share.

Comments