Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value from async method in python?

I have the following flask app:

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()

When I run this code I got TypeError: 'NoneType' object is not iterable. How to return my values converted to JSON?


1 Answers

You need to return your values in your run function for them to be available in test:

async def run():
   conn = await asyncpg.connect(db_url)
   values = await conn.fetch('''SELECT ... FROM ... WHERE ...;''')
   await conn.close()
   return values
like image 56
Pit Avatar answered Sep 02 '25 17:09

Pit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!