我试图重写代码以使其异步,对于通常的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)))