The difference between session and Scoped_session when manipulating database in SqlAlchemy

Source: Internet
Author: User
Tags scalar sesion

Tag: Port AAA Date View Source Tor Err mode package

Native session:
 fromSqlalchemy.ormImportSessionmaker fromSQLAlchemyImportCreate_engine fromSQLAlchemy applications. ModelsImportUsersengine=Create_engine ("Mysql+pymysql://root:[email Protected]:3306/pro6?charset=utf8", Max_overflow=0,#most connections created outside the connection pool sizePool_size=5,#Connection Pool Size)#From sqlalchemy.orm.session Import sessionsessionf= Sessionmaker (bind=engine) Session=sessionf ()Print(session) Obj1= Users (name='Ctz', email='[email protected]', extra='AAAA') Session.add (obj1) session.commit () session.close ()

Problem: Due to the inability to provide thread sharing, it is important to note at development time that you create your own session for each thread

Print sesion that he is the object of Sqlalchemy.orm.session.Session

View the source of the session to get:

classSession (_sessionclassmethods):"""manages persistence operations for orm-mapped objects.    The Session ' s usage paradigm is described at:d OC: '/orm/session '. """Public_methods= (        '__contains__','__iter__','Add','Add_all','begin','begin_nested',        'Close','Commit','Connection','Delete','Execute','expire',        'Expire_all','Expunge','Expunge_all','Flush','Get_bind',        'is_modified','bulk_save_objects','bulk_insert_mappings',        'bulk_update_mappings',        'Merge','Query','Refresh','rollback',        'scalar')
2.scoped_session
 fromSqlalchemy.ormImportSessionmaker fromSqlalchemy.ext.declarativeImportDeclarative_base fromSQLAlchemyImportCreate_engine fromSQLAlchemy applications. ModelsImportUsers fromSqlalchemy.ormImportScoped_sessionengine=Create_engine ("Mysql+pymysql://root:[email Protected]:3306/pro6?charset=utf8", Max_overflow=0,#most connections created outside the connection pool sizePool_size=5,#Connection Pool Size)sessionf=sessionmaker (bind=engine)#The Scoped_session encapsulates a two-value Session and registry,registry parentheses to perform the Threadlocalregistry __call__ method, if#there is a session in the current local thread to return to the session, no session is added to the local thread#self.registry () =sessionsession=scoped_session (sessionf)Print(session) Obj1=users (name='Ctz', email='[email protected]', extra='AAAA') Session.remove () Session.query_property ()

Pros: Supports thread safety and creates a session for each thread:

Two ways: Through local thread threading.local () and create a unique identity method (refer to Flask request source)

SOURCE Analysis:

First we put the Sesion object in the Scoped_session.

Sessionf=sessionmaker (Bind=engine)
Session=scoped_session (session)

First, the Scoped_session class
 class   Scoped_session (object): Session_ Factory  = None  def  __init__  (self, session_factory, Scopefunc=none):  #   The Session object passed over  self.session_factory =
    
      session_factory  
     #  
      Scopefunc unique label function  
     if  
      Scopefunc:se Lf.registry  =
      Scopedregistry (session_factory, Scopefunc)  
     else  
     : Self.registry  = Threadlocalregistry (session_fact Ory) 
    

First come in. Scopefunc uniquely identified as none, we pass the session as a parameter to the Threadlocalregistry,

In the Threadlocalregistry class
classthreadlocalregistry (scopedregistry):"""a:class: '.    Scopedregistry ' that uses a ' threading.local () "variable for storage. """    def __init__(self, createfunc):#The session object passed over.Self.createfunc =Createfunc self.registry=threading.local () #scoped_session. Registry () after executiondef __call__(self):Try:
#如果本地线程中有值的话直接将值返回,returnSelf.registry.valueexceptAttributeerror:
#没有值的话就示例话Session () and saves him to a local thread and returns the object of the instance#An object equivalent to the session () is added to the local threadval = Self.registry.value =Self.createfunc ()returnVal

where __call__ () is only executed when scoped_session.registry parentheses

So how do we call those methods?

def instrument (name):     def do (self, *args, * *Kwargs)        :return getattr (Self.registry (), name) (*args, * *  Kwargs)    return   do to in Session.public_methods:    SetAttr (scoped_session, meth, instrument (meth))

Where the session is Sqlalchemy.orm.session.Session

Public_methods = (        '__contains__','__iter__','Add','Add_all','begin','begin_nested',        'Close','Commit','Connection','Delete','Execute','expire',        'Expire_all','Expunge','Expunge_all','Flush','Get_bind',        'is_modified','bulk_save_objects','bulk_insert_mappings',        'bulk_update_mappings',        'Merge','Query','Refresh','rollback',        'scalar')

In the instrument function

Self.registry () helped us execute the ___call__ method in Threadlocalregistry and got the Sesion object


Method source code Example:
def Have (self):         return " value ")
    def Remove (self):         if Self.registry.has ():            self.registry (). Close ()        self.registry.clear ()

The actual two principles are the same is the first, but the second place the session in a local thread, for each process is set up a session, the implementation of thread safety

The difference between session and Scoped_session when manipulating database in SqlAlchemy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.