36

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
  • in this code, is it okay that test() function is not async? Commented Feb 1, 2024 at 8:16

1 Answer 1

30

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, is it necessary to return value after await conn.close() or I can return values and then await conn.close() ?
return exits the function, so the await would not be called. Maybe try yield values before calling await conn.close().
On second thought: what you probably want to do is loop.create_task(conn.close()) and still use return values. This will schedule the closing of the connection without waiting for it in your function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.