Reputation: 6328
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
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