从协程发出的嵌套列表返回

时间:2019-10-31 15:30:23

标签: python python-asyncio aio

我试图重写代码以使其异步,对于通常的I / O操作(MySQL查询),我使用aiomysql库。 为了防止将来出现key error等问题,我通过将键和值设置为属性来将字典转换为对象。 但是,当协程返回列表对象[[]]中的列表,而不仅仅是列表对象时,我遇到了一个问题。

  • 从函数列表中创建生成器不起作用,我收到异常

使用print()

输出功能
[<sqlobject.SQLObject object at 0x7f75a52476a0>, 
<sqlobject.SQLObject object at 0x7f75a5247668>, 
<sqlobject.SQLObject object at 0x7f75a52476d8]

列表理解后在协程外部输出

[[<sqlobject.SQLObject object at 0x7f75a52476a0>, 
<sqlobject.SQLObject object at 0x7f75a5247668>, 
<sqlobject.SQLObject object at 0x7f75a52476d8>
]]
# Dict to class converter
@asyncio.coroutine
    def selectall(self, loop, stmt, *args):
        try:
            with (yield from self.pool) as conn:
                cursor = yield from conn.cursor(aiomysql.DictCursor)
                yield from cursor.execute(stmt, *args)
                rows = yield from cursor.fetchall()
                new_items = [SQLObject(x) for x in rows]
                results = yield from new_items
                return results
        except:
            raise

# Result in loop executioner
result = loop.run_until_complete(
        asyncio.gather(pool_obj.selectall(loop, stmt)))

0 个答案:

没有答案