声明性SQLAlchemy在内存表中创建SQLITE

时间:2011-01-30 00:13:19

标签: python sqlite sqlalchemy declarative

这是我为应用程序设置数据库的方法(在Flask中):

from sqlalchemy.engine import create_engine
from sqlalchemy.orm import scoped_session, create_session
from sqlalchemy.ext.declarative import declarative_base

engine = None
db_session = scoped_session(lambda: create_session(bind=engine,
                                                   autoflush=False, autocommit=False, expire_on_commit=True))

Base = declarative_base()
Base.query = db_session.query_property()

def init_engine(uri, **kwargs):
    global engine
    engine = create_engine(uri, **kwargs)

    Base.metadata.create_all(bind=engine)

    return engine

如果我连接到已经创建了表的文件数据库,一切正常,但使用 sqlite:///:memory:作为目标数据库会给我:

OperationalError: (OperationalError) no such table: users u'DELETE FROM users' ()

在查询时如此:

UsersTable.query.delete()
db_session.commit()

我从单元测试中访问此代码。有什么问题?

由于

修改

应用程序的工作设置:

app = Flask(__name__)
app.config.from_object(__name__)
app.secret_key = 'XXX'

# presenters
from presenters.users import users

# register modules (presenters)
app.register_module(users)

# initialize the database
init_engine(db)

1 个答案:

答案 0 :(得分:3)

您发布的代码不包含任何表/类声明。你确定声明是在调用init_engine()之前完成的吗?