Detailed SQlALchemy session

Series:

  1. Python SQLAlchemy Getting Started Tutorial

concept

session for creating a session between the program and the database, all objects are required to load and save through the session object.

Create a factory by sessionmaker call and associated Engine to ensure that each session can use the connection resource Engine:

from sqlalchemy.orm import sessionmaker

# 创建session
DbSession = sessionmaker(bind=engine)
session = DbSession()

operating

Common methods of operation session include:

  1. flush: pre-commit, committed to the database file, has not yet written to the database file
  2. commit: commits a transaction, the memory data directly into the database
  3. rollback: Rollback
  4. close: Close

When a transaction, the need to pay attention to two points:

  1. When an exception occurs during transaction processing, a rollback operation, otherwise it will error at the next operation:
Can’t reconnect until invalid transaction is rolled back 
  1. Under normal circumstances, after a transaction is completed to close the session, in order to ensure the accuracy of data manipulation.

Packaging context of a method recommended:

from contextlib import contextmanager

@contextmanager
def session_maker(session=session):
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()

transfer:

def update_user():
    with session_maker() as db_session:
        db_session.query(Users).filter_by(name='test2').update({'email': '[email protected]'})

Thread Safety

session is not thread safe, and we usually session objects are global, then in multiple threads when multiple threads share a session, data processing error occurs.

In order to ensure thread safety, use scoped_session method:

db_session = scoped_session(sessionmaker(bind=engine))

Internal principle

session object contains three important parts:

  1. Identity Mapping (Identity Map)
  2. State of the object / status tracking
  3. Affairs

Identity Mapping

Identity mapping is a collection associated with the ORM, by identity mapping to ensure the accuracy of database operations.

Specific implementation principle is: Maintaining a Python dictionary (IdentityMap), associated with the Session object to the mapping database ID, when the application you want to get a session object, if the object does not exist, to identify and map will load the object cache, If the object already exists, the direct access. Such benefits are:

  1. It has been requested before the session object cached, need not be connected to load several times, causing extra overhead;
  2. Avoiding data inconsistencies

Status Tracking

A Session object from creation to destruction, in turn experienced four states, namely:

  1. Transient: just out of the new object is not in session, nor saved to the database.
  2. Pending: transient object after a call to add, will become a pending state, then will join the scope of supervision sqlalchemy, the data is not updated to the database.
  3. Persistent: This status indicates that the database has recorded the object in both cases the object is in the state: First, refresh pending objects by flush () method, the second is to get an object from the database query ().
  4. Detached: After the session transaction commit, all the objects will be Detached state.

The so-called status tracking is tracking more than four states, to ensure the accuracy of the data and discarded objects in a reasonable time in order to ensure a reasonable cost, then specifically how to achieve it?

We can see only in pending status, data inconsistencies memory data and database objects, and when Persistent state, memory data and database data has been consistent, then at any time thereafter drops the object data are possible, then We need to find the right time to discard objects, too early or too late has its drawbacks. So, let the garbage collector to make a decision to release the object in memory is not enough when the recovery of memory.

Session object using a weak reference mechanism, the so-called weak references, that is, in the case cited save the object, the object may still be garbage collected. When accessing an object by reference, at some point, the object may or may not exist, if the object does not exist, re-load the object from the database. And if you do not want the object to be recovered, only to save another strong reference to an object.

The session object includes three attributes:

  1. new: just joined an object session
  2. dirty: just been modified object
  3. deleted: Objects in the session to be deleted

Three attributes common feature is the memory of the data and database data is inconsistent, that is, the object is in the pending state, which also indicates that the session save strong reference to all the objects in a pending state.

the above.

Code may refer to: My GitHub

Guess you like

Origin www.cnblogs.com/ybjourney/p/11876595.html