如何从python中的异步方法返回值?

时间:2017-03-16 11:16:07

标签: python asynchronous flask

我有以下烧瓶应用程序:

async def run():
   conn = await asyncpg.connect(db_url)
   values = await conn.fetch('''SELECT ... FROM ... WHERE ...;''')
   await conn.close()

@app.route('/')
def test():
    loop = asyncio.get_event_loop()
    res = loop.run_until_complete(run())
    return json.dumps([dict(r) for r in res]) 

if __name__ == '__main__':
    app.run()

当我运行此代码时,我得到TypeError: 'NoneType' object is not iterable。如何将我的values转换为JSON?

1 个答案:

答案 0 :(得分:12)

您需要在run函数中返回您的值,才能在test中找到它们:

async def run():
   conn = await asyncpg.connect(db_url)
   values = await conn.fetch('''SELECT ... FROM ... WHERE ...;''')
   await conn.close()
   return values