Sławomir Lenart
Sławomir Lenart

Reputation: 8377

how verify if sqlalchemy session is configured?

standard/normal configuration of sqlalchemy session:

from sqlalchemy.orm import scoped_session, sessionmaker

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))  # 0
engine = engine_from_config(config, 'sqlalchemy.')

try:
   DBSession.query('1').scalar()    # 1
except UnboundExecutionError:
   pass  # expected here - session is not bound

DBSession.configure(bind=engine)   # 2

try:
   DBSession.query('1').scalar()   # 3
except UnboundExecutionError:
   pass  # not expected here - session is bound ?

any attempt to use unbound session will finish with broken? session object - to use session I must create new one with line #0.

how should I check if session object is not bound and keep just one object all the time?

Upvotes: 0

Views: 738

Answers (1)

loopbackbee
loopbackbee

Reputation: 23322

You should keep a reference to your session factory.

Instead of

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))  # 0
engine = engine_from_config(config, 'sqlalchemy.')

you could do

engine = engine_from_config(config, 'sqlalchemy.')
Session= sessionmaker(extension=ZopeTransactionExtension(), bind=engine)
DBSession= Session()

Everytime you need a session, you simply call Session(). There's no need to have a singleton.

Upvotes: 1

Related Questions