python - Sql Alchemy QueuePool 限制溢出

标签 python session sqlalchemy zope connection-timeout

我有一个返回 TimeOut 的 Sql Alchemy 应用程序:

TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30

我在另一篇文章中读到,当我不关闭 session 时会发生这种情况,但我不知道这是否适用于我的代码:

我在init.py中连接数据库:

from .dbmodels import (
    DBSession,
    Base,    

engine = create_engine("mysql://" + loadConfigVar("user") + ":" + loadConfigVar("password") + "@" + loadConfigVar("host") + "/" + loadConfigVar("schema"))

#Sets the engine to the session and the Base model class
DBSession.configure(bind=engine)
Base.metadata.bind = engine

然后在另一个 python 文件中,我在两个函数中收集一些数据,但使用的是我在 init.py 中初始化的 DBSession:

from .dbmodels import DBSession
from .dbmodels import resourcestatsModel

def getFeaturedGroups(max = 1):

    try:
        #Get the number of download per resource
        transaction.commit()
        rescount = DBSession.connection().execute("select resource_id,count(resource_id) as total FROM resourcestats")

        #Move the data to an array
        resources = []
        data = {}
        for row in rescount:
            data["resource_id"] = row.resource_id
            data["total"] = row.total
            resources.append(data)

        #Get the list of groups
        group_list = toolkit.get_action('group_list')({}, {})
        for group in group_list:
            #Get the details of each group
            group_info = toolkit.get_action('group_show')({}, {'id': group})
            #Count the features of the group
            addFesturedCount(resources,group,group_info)

        #Order the FeaturedGroups by total
        FeaturedGroups.sort(key=lambda x: x["total"],reverse=True)

        print FeaturedGroups
        #Move the data of the group to the result array.
        result = []
        count = 0
        for group in FeaturedGroups:
            group_info = toolkit.get_action('group_show')({}, {'id': group["group_id"]})
            result.append(group_info)
            count = count +1
            if count == max:
                break

        return result
    except:
        return []


    def getResourceStats(resourceID):
        transaction.commit()
        return  DBSession.query(resourcestatsModel).filter_by(resource_id = resourceID).count()

session 变量是这样创建的:

#Basic SQLAlchemy types
from sqlalchemy import (
    Column,
    Text,
    DateTime,
    Integer,
    ForeignKey
    )
# Use SQLAlchemy declarative type
from sqlalchemy.ext.declarative import declarative_base

#
from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    )

#Use Zope' sqlalchemy  transaction manager
from zope.sqlalchemy import ZopeTransactionExtension

#Main plugin session
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))

因为 session 是在 init.py 和后续代码中创建的,所以我只是使用它;在什么时候我需要关闭 session ?或者我还需要做什么来管理池大小?

最佳答案

您可以通过在函数create_engine中添加参数pool_size和max_overflow来管理池大小

engine = create_engine("mysql://" + loadConfigVar("user") + ":" + loadConfigVar("password") + "@" + loadConfigVar("host") + "/" + loadConfigVar("schema"), 
                        pool_size=20, max_overflow=0)

引用是here

您无需关闭 session ,但应在您的事务完成后关闭连接。 替换:

rescount = DBSession.connection().execute("select resource_id,count(resource_id) as total FROM resourcestats")

作者:

connection = DBSession.connection()
try:
    rescount = connection.execute("select resource_id,count(resource_id) as total FROM resourcestats")
    #do something
finally:
    connection.close()

引用是here

另外,请注意,mysql 已经过时的连接会在特定时间后关闭(此时间可以在 MySQL 中配置,我不记得默认值),因此您需要将 pool_recycle 值传递给引擎创建

关于python - Sql Alchemy QueuePool 限制溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24956894/

相关文章:

python - SqlAlchemy/mysql 可选Where子句

python - Pandas - Groupby 或将多个数据帧剪切到垃圾箱

python - QGridlayout 和 QGroupbox 对齐

python - 数据帧到 np.array - IndexError : tuple index out of range

python - 找到要使用的图像?

session - 该 session 如何在asp.net中工作?

python - 基于 Flask 的网站出现奇怪的 AttributeError

python - AttributeError : 'IntegrityError' object has no attribute 'message' SQLAlchemy

ruby-on-rails - 浏览器关闭时销毁 session - Ruby on Rails

java - 如何访问标准 Java 类中的 session 状态?