Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use `session_maker` and when to use `Session` in sqlalchemy

Sqlalchemy's documentation says that one can create a session in two ways:

from sqlalchemy.orm import Session
session = Session(engine)

or with a sessionmaker

from sqlalchemy.orm import session_maker
Session = session_maker(engine)
session = Session()

Now in either case one needs a global object (either the engine, or the session_maker object). So I do not really see what the point of the session_maker is. Maybe I am misunderstanding something.

I could not find any advice when one should use one or the other. So the question is: In which situation would you want to use Session(engine) and in which situation would you prefer session_maker?

like image 773
Felix B. Avatar asked Dec 05 '25 15:12

Felix B.


1 Answers

The docs describe the difference very well:

Session is a regular Python class which can be directly instantiated. However, to standardize how sessions are configured and acquired, the sessionmaker class is normally used to create a top level Session configuration which can then be used throughout an application without the need to repeat the configurational arguments.

like image 119
rfkortekaas Avatar answered Dec 07 '25 04:12

rfkortekaas