Noor
Noor

Reputation: 20130

SQLAlchemy Session Object

I'm having a confusion about the session object in SQLAlchemy. Is it like the PHP session where a session is all the transactions of a users or is a session an entity which scopes the lifetime of a transaction.

For every transaction in SQLAlchemy, is the procedure as follows: -create and open session -perform transaction -commit or rollback -close session

So, my question is, for a client, do we create a single session object, or a session object is created whenever we have a transaction to perform

Upvotes: 1

Views: 713

Answers (1)

Mark Hildreth
Mark Hildreth

Reputation: 43061

I would be hesitant to compare a SQLAlchemy session with a PHP session, since typically a PHP session refers to cookies, whereas SQLAlchemy has nothing to do with cookies or HTTP at all.

As explained by the documentation:

A Session is typically constructed at the beginning of a logical operation where database access is potentially anticipated.

The Session, whenever it is used to talk to the database, begins a database transaction as soon as it starts communicating. Assuming the autocommit flag is left at its recommended default of False, this transaction remains in progress until the Session is rolled back, committed, or closed. The Session will begin a new transaction if it is used again, subsequent to the previous transaction ending; from this it follows that the Session is capable of having a lifespan across many transactions, though only one at a time. We refer to these two concepts as transaction scope and session scope.

The implication here is that the SQLAlchemy ORM is encouraging the developer to establish these two scopes in his or her application, including not only when the scopes begin and end, but also the expanse of those scopes, for example should a single Session instance be local to the execution flow within a function or method, should it be a global object used by the entire application, or somewhere in between these two.

As you can see, it is completely up to the developer of the application to determine how to use the session. In a simple desktop application, it might make sense to create a single global session object and just keep using that session object, committing as the user hits "save". In a web application, a "session per request handled" strategy is often used. Sometimes you use both strategies in the same application (a session-per-request for web requests, but a single session with slightly different properties for background tasks).

There is no "one size fits all" solution for when to use a session. The documentation does give hints as to how you might go about determining this.

Upvotes: 3

Related Questions