【发布时间】:2015-06-16 08:10:46
【问题描述】:
我正在尝试使用 flask-sqlalchemy 来管理我预先存在的 mysql 数据库,并且我有一个名为 content 的表。这是我的代码 sn-p。
# coding:utf-8
from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
...
app = Flask(__name__)
bootstrap = Bootstrap(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://...'
db = SQLAlchemy(app)
class Content(db.Model):
__table__ = db.Model.metadata.tables['content']
def __repr__(self):
return '<title %r>' % self.title
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
...
if __name__ == '__main__':
app.run(debug=True)
当我运行上面的代码时,我得到了这个错误
Traceback (most recent call last):
File "hello.py", line 13, in <module>
class Content(db.Model):
File "hello.py", line 14, in Content
__table__ = db.Model.metadata.tables['content']
KeyError: 'content'
我们将不胜感激。
【问题讨论】:
-
KeyError显示您以Content访问该表,而代码 sn-p 显示您以content访问它 - 两种方式都会导致KeyErrors 吗? -
@SeanVieira 实际上我复制了错误的报告,我已经修改了我的问题。请查看。
-
您为什么使用
metadata.tables而不是仅仅使用__table__ = 'content'? -
@SeanVieira 我从这里学到的。 stackoverflow.com/a/19064993/4144064.
-
1.您在创建模型之前是否致电
db.Model.metadata.reflect(db.engine)? 2.content表是否已经存在于DB中?