自学内容网 自学内容网

sqlalchemy The transaction is active - has not been committed or rolled back.

连接池参考

参考:https://blog.csdn.net/SunJW_2017/article/details/129332393

1、因为使用了连接池,没有释放

2、解决方法:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from greenlet import getcurrent as get_ident


class Service(object):
    def __init__(self):
        from common import con_sql

        self.engine = create_engine(
            con_sql,
            echo=true,  # 显示SQL
            # poolclass=NullPool,  # 不使用连接池
            pool_size=5,  # 连接池大小
            max_overflow=5,  # 允许增加连接数
            pool_pre_ping=True,  # 在每次使用连接进行数据库操作前,先检验一下连接是否有效。有效就直接使用;无效则重新连接
            pool_recycle=7200  # 多久之后对线程池中的线程进行一次连接的回收(重置),单位(秒)
        )

        self.session_factory = sessionmaker(bind=self.engine)
        self.db_session = scoped_session(self.session_factory, get_ident)

    def __del__(self):
        self.dispose()

    def dispose(self):
        try:
            if self.db_session:
                self.db_session.remove()
                self.db_session.close()
                self.db_session = None
            if self.session_factory:
                self.session_factory = None
            if self.engine:
                self.engine.dispose()
                self.engine = None
        except Exception as _ex:
            pass


原文地址:https://blog.csdn.net/XinShun/article/details/145184794

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!