8

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)
1
  • What's the output if you add "print Base.metadata.tables.keys()" just before .create_all() ?
    – jd.
    Feb 1, 2011 at 15:19

1 Answer 1

5

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

1
  • 1
    You are quite right! I have updated the question with the 'correct' order of execution. Thanks @jd
    – Radek
    Jan 31, 2011 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.