What's session?

  • As an ORM, SQLAlchemy enables you to manipulate database records as Python objects.
  • In the most general sense, the Session establishes all conversations with the database and represents a “holding zone” for all the objects which you’ve loaded or associated with it during its lifespan.

現在流行對DB的操作是透過ORM而不是SQL,而在Python中是透過成立一個Session的Object來對DB進行操作,等等我們會記錄一下幾個常用的Session function。

Life cycle

  • However in most web applications, the established pattern is to begin and end the Session with each http request.


Flushing objects

  • Flushing means to push all object changes to the database. (Note that this does not necessarily mean that changes have been made to the database records)
  • Pushing object changes to the database means your database now holds the changes in its transaction buffer
  • The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what session.commit() does).
  • When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds. By default, Session objects autoflush their operations, but this can be disabled.
  • autocommit: False => not call commit, True: call commit auto

Flushing 表示先暫時把改變的動作送到 transaction buffer。 但真正要改變DB的內容還是要透過Commit。 這表示如果妳透過 Flushing 送到 DB 的值是可以取消的。

接著如果你要 Query DB的相關資訊,除了DB的內容之後還包含了在transaction buffer但尚未commit的資訊。

Expiring objects

  • A key behaviour of expiring is that all un-flushed changes to the object is discarded and not persisted to the database
  • Objects are automatically expired already whenever the Session ends. This means if there is a call to db.session.commit() or db.session.rollback() (automatically at the end of a HTTP request in the case of a web application), all objects are expired.

expire 系列的 function 我自己是比較少用啦,簡單的來說就是把還沒 flushing 的結果通通變成無效這樣。

Refreshing objects

  • Basically, refreshing means to expire and then immediately get the latest data for the object from the database.

refreshing 是立刻讓尚未 flushing 的操作變成無效,然後立刻再去 Database 中拿最新的資料。


  • db.session.commit() is basically 2 steps in one:
  • Flushing - push changes from SQLAlchemy's in-memory representation to the database transaction buffer
  • Commit - persist changes from your database's transaction buffer into the database, ie inserting / updating / deleting.

Commit 應該是所有 function 裡面中最熟悉的一個了,基本上就是永久更變database的值,沒辦法 rollback 了。


  • Used when you may have more than 1 in-memory objects which map to the same database record with some key.
  • Merging causes the in-memory objects to be synchronised with each other, does not necessarily persist to the database.

Merging 會發生的情況通常是你有多個 memory objects 對應到相同的 Database record,但他們彼此之間又需要同步時。