> -----Original Message-----
> From: [email protected] 
> [mailto:[email protected]] On Behalf Of Daniel Robbins
> Sent: 22 March 2010 20:45
> To: [email protected]
> Subject: Re: [sqlalchemy] recommended declarative method 
> design pattern for sessions
> 
> On Mar 22, 2010, at 5:10 AM, King Simon-NFHD78 wrote:
> 
>       
>       See the 'How can I get the Session for a certain 
> object' question at
>       
> http://www.sqlalchemy.org/docs/session.html#frequently-asked-questions
>       
>       Basically, in your FindFriends method, replace:
>       
>         session = Session()
>       
>       with:
>       
>         session = Session.object_session(self)
>       
> 
> 
> The reference documentation seems to indicate that 
> Session.object_session() will return the existing session if 
> one exists, rather than providing a new session that must be 
> separately closed.
> 
> Is this correct? If so, then FindFriends() should not close 
> the session acquired via Session.object_session(obj), correct?
> 
> Is it possible for object_session() to return None if the 
> object's session was previously close()d?
> 
> Thanks,
> 
> Daniel
> 

object_session does indeed return the session that the instance is
already bound to (so you shouldn't close it). I didn't know what
object_session would return if the original session had been closed, so
I tried it:

    import sqlalchemy as sa
    import sqlalchemy.orm as saorm
    import sqlalchemy.ext.declarative as decl

    Base = decl.declarative_base()

    class User(Base):
        __tablename__ = 'user'
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(sa.String)

    engine = sa.create_engine('sqlite://')
    Base.metadata.create_all(bind=engine)
    Session = saorm.sessionmaker(bind=engine)

    sess = Session()
    print "Original session is", sess

    u1 = User(name='Daniel')
    sess.add(u1)
    sess.commit()

    print "Before closing session, object_session returns",
    print Session.object_session(u1)

    sess.close()
    print "After closing session, object_session returns",
    print Session.object_session(u1)


Which produced the following output:

Original session is <sqlalchemy.orm.session.Session object at
0xb705a36c>
Before closing session, object_session returns
<sqlalchemy.orm.session.Session object at 0xb705a36c>
After closing session, object_session returns None


So I guess object_session already does what you want.

Hope that helps,

Simon

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to