sqlalchemy multithreaded create session

1, based on threding.local, recommended

from sqlalchemy.orm Import sessionmaker
 from SQLAlchemy Import create_engine
 from sqlalchemy.orm Import scoped_session
 from Models Import Student
 from Threading Import the Thread 

Engine = create_engine (
         " MySQL + pymysql: // root: password @ 127.0.0.1:? 3306 / database charset = utf8 " , 
        max_overflow = 0,   # than connecting up to the outer size of the connection pool created 
        pool_size =. 5,   # connection pool size 
        pool_timeout = 30,   #No thread pool up to the waiting time, otherwise an error 
        pool_recycle = -1   # long thread after thread pool for recycling (reset) once connected 
    ) 
SessionFactory = sessionmaker (the bind = Engine) 
the session = scoped_session (SessionFactory) 


DEF Task (): 
    RET = session.query (Student) .all ()
     # connect back to the connection pool 
    session.remove () 



for I in Range (20 is ): 
    T = the Thread (target = Task) 
    t.start ()

2, based on multi-threaded

from sqlalchemy.orm Import sessionmaker
 from SQLAlchemy Import create_engine
 from Models Import Student
 from Threading Import the Thread 

Engine = create_engine (
         " MySQL + pymysql: // root: password @ 127.0.0.1:? 3306 / database = utf8 charset " , 
        max_overflow = 0,   # more than connecting the external connection pool sizes up to create 
        pool_size = 5,   # connection pool size 
        pool_timeout = 30,   # pool no thread waiting time at most, otherwise an error 
        pool_recycle = -1   #After long threads in the pool to recover (reset) once connected 
    ) 
SessionFactory = sessionmaker (the bind = Engine) 

DEF Task ():
     # to get a connection pool connect 
    the session = SessionFactory () 
    RET = session.query ( Student) .all ()
     # connect back to the connection pool 
    Session.close () 



for I in Range (20 is ): 
    T = the Thread (target = Task) 
    t.start ()

 

Guess you like

Origin www.cnblogs.com/wt7018/p/11617864.html