首页 > 解决方案 > 如何在 peewee-orm 中使用 ThreadPoolExecutor 处理数据库连接池?

问题描述

我在脚本中使用peewee和 mariadb 数据库,脚本查看 db 表并将该查询中的数据提交到 ThreadPoolExecutor。工作人员本身也需要查询数据库。在所有期货完成后,脚本再次从头开始。

当我使用单个连接时,一切正常,但由于我的工作工作主要是网络 IO,我觉得所有工作线程的单个连接将成为瓶颈。

如果我更改为数据库池,我可以监控连接正在增加,直到我收到来自 peewee 的错误“打开的连接太多”。连接本身永远不会关闭。这符合 peewee 的文档

但是我不知道如何从我的工作函数内部手动打开和关闭数据库连接。

我尝试在 models.py 中使数据库变量成为全局变量,然后我可以在我的工作人员中访问该对象,但是观察我的数据库上所有打开的连接让我意识到 .close()/.open() 在这种情况下没有效果。

我还将所有内容粘贴到一个文件中,我仍然无法手动打开/关闭连接。

文档仅提供有关如何使用具有不同 Web 框架的池的示例。

我的应用程序简化了

#app.py
from models.models import MyTableA, MyTableB

def do_work(data):
    MyTableB.create(name="foo")

def main()
    logger = logging.getLogger()
    data = MyTableA.select().dicts()

    with ThreadPoolExecutor(8) as executor:
        future_to_system = {executor.submit(do_work, d): d.id for d in data}
        
        for future in as_completed(future_to_system):
            system = future_to_system[future]
            try:
                future.result()
            except Exception as exc:
                logger.info('%r generated an exception: %s' % (system, exc))

            else:
                logger.debug('%r result is %s' % (system, "ok"))

if __name__ == '__main__':
    main()

模型.py

from peewee import *
from playhouse.pool import PooledMySQLDatabase

#uncomment this line to use pool
#database = PooledMySQLDatabase('db_name', **{'charset': 'utf8', 'sql_mode': 'PIPES_AS_CONCAT', 'use_unicode': True, 'user': 'user', 'passwd': 'pass', 'max_connections': 32, 'stale_timeout': 300})

#comment that line to use pool
database = PooledMySQLDatabase('db_name', **{'charset': 'utf8', 'sql_mode': 'PIPES_AS_CONCAT', 'use_unicode': True, 'user': 'user', 'passwd': 'pass'})




class UnknownField(object):
    def __init__(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = database

class MyTableA(BaseModel):
    name = CharField()

    class Meta:
        table_name = 'my_table'

class MyTableB(BaseModel):
    name = CharField()


    class Meta:
        table_name = 'my_table'

如果有人知道如何将 peewee 的连接池与 Threadpoolexecutor 一起使用,我将非常感激。

标签: pythonpython-3.xdatabasemultithreadingpeewee

解决方案


我在这里找到了解决方案

模型.py

from peewee import *


class UnknownField(object):
    def __init__(self, *_, **__): pass

class BaseModel(Model):
    class Meta:
        database = None

class MyTableA(BaseModel):
    name = CharField()

    class Meta:
        table_name = 'my_table'

class MyTableB(BaseModel):
    name = CharField()

    class Meta:
        table_name = 'my_table'

应用程序.py

from playhouse.pool import PooledMySQLDatabase
from models.models import MyTableA, MyTableB

def do_work(data, db):
    with db:
        MyTableB.create(name="foo")

def main()
    logger = logging.getLogger()
    

    database = PooledMySQLDatabase('db_name', **{'charset': 'utf8', 'sql_mode': 'PIPES_AS_CONCAT', 'use_unicode': True, 'user': 'user', 'passwd': 'pass', 'max_connections': 32, 'stale_timeout': 300})

    database.bind(
        [
            MyTableA, MyTableB
        ]
    )

    with database:
        data = MyTableA.select().dicts()


    with ThreadPoolExecutor(8) as executor:
        future_to_system = {executor.submit(do_work, d): d.id for d in data}
        
        for future in as_completed(future_to_system):
            system = future_to_system[future]
            try:
                future.result()
            except Exception as exc:
                logger.info('%r generated an exception: %s' % (system, exc))

            else:
                logger.debug('%r result is %s' % (system, "ok"))

if __name__ == '__main__':
    main()

推荐阅读