在SQLAlchemy数据库中提交时获取错误

时间:2016-11-24 10:25:16

标签: python flask

我正在研究一个小瓶子tutorial,在添加一些数据后,我尝试在数据库内部提交。而且,在那段时间里,我收到以下错误,

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user [SQL: u'INSERT INTO user (nickname, email) VALUES (?, ?)'] [parameters: ('john', 'john@email.com')]

此表格代表models.py文件中提供的mdoel:

from app import db

class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    posts = db.relationship('Post', backref='author', lazy='dynamic')

    def __repr__(self):
        return '<User %r>' % (self.nickname)


class Post(db.Model):   

    id = db.Column(db.Integer, primary_key = True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '<Post %r>' % (self.body)

似乎User表不存在或已创建。所以,我在shell中运行了以下脚本,

from sqlalchemy import create_engine
from config import SQLALCHEMY_DATABASE_URI

engine = create_engine(SQLALCHEMY_DATABASE_URI)

from sqlalchemy import MetaData
m = MetaData()
m.reflect(engine)
for table in m.tables.values():
    print(table.name)
    for column in table.c:
        print(column.name)

我得到的结果如下,

migrate_version
repository_id
repository_path
version

post
id
body
timestamp
user_id

user
id
nickname
email

这意味着user表已创建并存在。这里有什么问题以及如何解决?

我有第二个脚本也会产生相同的结果:

from sqlalchemy import inspect
inspector = inspect(engine)

for table_name in inspector.get_table_names():
   for column in inspector.get_columns(table_name):
       print("Column: %s" % column['name'])

0 个答案:

没有答案