开发者

Declarative SQLAlchemy CREATE SQLITE in memory tables

开发者 https://www.devze.com 2023-02-08 00:08 出处:网络
This is how I setup my database for an application (in Flask): from sqlalchemy.engine import create_engine

This is how I setup my database for an application (in 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

If I connect to a file database that has had tables created already, everything works fine, but using sqlite:///:memory: as a target database gives me:

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

when querying like so for ex.:

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

I am accessing this code from a unit test. What is the problem?

Thanks

Edit:

Working setup of the application:

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)


The code you posted doesn't contain any table/class declaration. Are you sure that the declaration is done before init_engine() is called?

0

精彩评论

暂无评论...
验证码 换一张
取 消