sqlalchemy 多线程 创建session

时间:2019-10-02
本文章向大家介绍sqlalchemy 多线程 创建session,主要包括sqlalchemy 多线程 创建session使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、基于threding.local,推荐使用

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session
from models import Student
from threading import Thread

engine = create_engine(
        "mysql+pymysql://root:密码@127.0.0.1:3306/数据库?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
    )
SessionFactory = sessionmaker(bind=engine)
session = scoped_session(SessionFactory)


def task():
    ret = session.query(Student).all()
    # 将连接交还给连接池
    session.remove()



for i in range(20):
    t = Thread(target=task)
    t.start()

2、基于多线程

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Student
from threading import Thread

engine = create_engine(
        "mysql+pymysql://root:密码@127.0.0.1:3306/数据库?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
    )
SessionFactory = sessionmaker(bind=engine)

def task():
    # 去连接池中获取一个连接
    session = SessionFactory()
    ret = session.query(Student).all()
    # 将连接交还给连接池
    session.close()



for i in range(20):
    t = Thread(target=task)
    t.start()

原文地址:https://www.cnblogs.com/wt7018/p/11617864.html