Discuss / Python / __pool.get()什么意思

__pool.get()什么意思

Topic source

在aiomysql关于pool的文档中也没有找到这个函数,哪位大神能给解释下

select和execute都要关闭数据库连接

async def select(sql, args, size=None):
    log(sql, args)
    global __pool
    async with __pool.get() as conn:
        try:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                await cur.execute(sql.replace('?', '%s'), args or ())
                if size:
                    rs = await cur.fetchmany(size)
                else:
                    rs = await cur.fetchall()
        except BaseException as e:
            raise
        finally:
            conn.close()
        logging.info('rows returned: %s' % len(rs))
        return rs

async def execute(sql, args, autocommit=True):
    log(sql)
    async with __pool.get() as conn:
        if not autocommit:
            await conn.begin()
        try:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                await cur.execute(sql.replace('?', '%s'), args)
                affected = cur.rowcount
            if not autocommit:
                await conn.commit()
        except BaseException as e:
            if not autocommit:
                await conn.rollback()
            raise
        finally:
            conn.close()
        return affected

这是测试代码

@asyncio.coroutine
def test(loop):
    yield from orm.create_pool(loop=loop, user='www-data', password='www-data', db='awesome')

    r = yield from User().find('0014853115903445bae639a21ef4aa788b4ab5381af387e000')

    print(r)

loop = asyncio.get_event_loop()
loop.run_until_complete(test(loop))

Hello_棋哥

#3 Created at ... [Delete] [Delete and Lock User]
async with __pool.get() as conn:

AttributeError: '_PoolContextManager' object has no attribute 'get' 同样的错误,以为是aiomysql版本问题,但好像不是。你怎么解决的?

Hello_棋哥

#4 Created at ... [Delete] [Delete and Lock User]

__pool = await aiomysql.create_pool 漏掉了关键字: await,加上就好了。


  • 1

Reply