lithuak
lithuak

Reputation: 6328

SQLAlchemy: does session creation create new connection?

I'm trying to understand what is the right way of using Session. If creating the session with

session = Session()

creates new connection to db each time, then I must try to reuse my session for several transactions, otherwise I can create it frequently.

Can you help me with this?

Upvotes: 2

Views: 1227

Answers (1)

Mark Hildreth
Mark Hildreth

Reputation: 43071

SQLAlchemy has built-in connection pooling for the engine that you make (a connection is reused if already available).

The "session" itself is bound to an engine:

# create a configured "Session" class
Session = sessionmaker(bind=some_engine)

# create a Session
session = Session()

Therefore, the session will use the default connection pooling automatically; you don't need to do anything special to gain the benefits of this feature.

You can read more about how it works (and, if you wish, how to tune the connection pool to modify values such as connection timeout and pool size) in the documentation.

Upvotes: 3

Related Questions