9

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() ? Commented 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?

Sign up to request clarification or add additional context in comments.

1 Comment

You are quite right! I have updated the question with the 'correct' order of execution. Thanks @jd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.