views:

293

answers:

1

Updated:

Hi all,

Going through the Werkzeug link text tutorial, got stack with creating SQLAlchemy session using sessionmaker() instead of create_session() as recommended.

Note: it is not about SA, it is about Werkzeug.

Werkzeug tutorial:

session = scoped_session(lambda: create_session(bind=application.database_engine,
    autoflush=True, autocommit=False), local_manager.get_ident)

I asked how to achieve the same using sessionmaker():

As a result guys from #pocoo RCI helped me with this:

session = scoped_session(lambda: sessionmaker(bind=application.database_engine)(),
    local_manager.get_ident)

without () at the end of sessionmaker(**args) it kept giving me an error:

RuntimeError: no object bound to application

P.S. if delete lambda it will not work.

+2  A: 

sessionmaker() returns a session factory, not a session itself. scoped_session() takes a session factory as argument. So just omit the lambda: and pass the result of sessionmaker() directly to scoped_session().

Ants Aasma
Didn't mention it, I am playing with Werkzeug lib and SA. I am trying to adopt SA sessionmaker() instead of session_create() as SA Tutorial recommends to do it.Guys from #pocoo IRC helped me but I still didn't get it what the trick was it. They added "()" at the end of sessionmaker() and now it works.session = scoped_session(lambda: sessionmaker(bind=application.database_engine, autoflush=True, autocommit=False)(), local_manager.get_ident)
VVP
You're making more work for yourself, your code's readers, and your python interpreter by writing it that way instead of listening to Ants Aasma. You're also breaking your `scoped_session`. Your code creates a `sessionmaker`, and then calls it (returning a session), and passes that session in a lambda to `scoped_session`. So each time `scoped_session` tries to return a new session, it actually returns the same session. Omit the `lambda`, and drop the () from the end of your sessionmaker call. `scoped_session(sessionmaker(*args))`
jcdyer