参考:flask/sqlalchemy - OperationalError: (sqlite3.OperationalError) no such table
在用Flask写一个简单的py文件,做一个表单时,发现在login界面登陆的时候,出现:
OperationalError: (sqlite3.OperationalError) no such table: ...
错误,这个问题肯定是与数据库有关的;于是review了一下代码,关于数据库ORM的声明类Switches如下:
class Switches(db.Model):
__tablename__ = 'Switches'
sid = db.Column(db.Integer, primary_key=True)
sname = db.Column(db.String, unique=True, index=True)
#sprice = db.Column(db.Integer)
def __repr__(self):
print('<Switch_id %d>' % id)
两列Column,一个主key叫做sid,外加一个属性sname,没有问题;也排除了app.config的问题,那么就是视图函数中的问题了。
但是看上去也没有问题:
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
sw = Switches.query.filter_by(sname=form.name.data).first() # filter the DB
if sw is None:
sw = sw(sname=form.name.data)
db.session.add(sw)
session['known'] = False
else:
session['known'] = True
session['name'] = form.name.data
return redirect(url_for('myindex'))
return render_template('myindex.html', form=form, name=session.get('name'),
known=session.get('known', False))
逻辑语句if内是对表单的具体操作,在Swicthes数据库中找名字为输入数据的tuple,然后进行相关操作。
于是乎求助搜索引擎,在参考的那篇文章中回答者给出了这样的解释:
You're supposed to initialize/create the tables first. Please read the Creating the Database article in the official Flask documentation:
Such systems need a schema that tells them how to store that information. So before starting the server for the first time it’s important to create that schema.
Here's Flask's example of using a schema SQL script to create the database, tables, etc:
sqlite3 /tmp/flaskr.db < schema.sql
The recommended way is to use db.create_all() within your app. For example, see: https://github.com/hypatia-software-org/staticfuzz/blob/master/staticfuzz.py#L391
大意是数据库没有创建这张表,一个推荐的解决方法是加入db.create_all()
语句来创建表。
2017.3.30