19

I would like to know if it's possible to call an async function def get_all_allowed_systems in create_app function so that I have access to the database entries of ALLOWED_SYSTEMS populated by get_all_allowed_systems call. I have a limitation that I can't make create_app as async function.

async def get_all_allowed_systems(app):
    global ALLOWED_SYSTEMS
    operation = prepare_exec(app.config.get_all_systems_procedure)
    ALLOWED_SYSTEMS = (await app['database'].execute(operation)).all()

def create_app():
    app = App(config=Config)
    app['database'] = AioDatabase(**app.config.dict('db_'))
    app['app_database'] = AioDatabase(app.config.app_db_url)
    get_all_allowed_systems(app)
    print(ALLOWED_SYSTEMS)

1 Answer 1

32

In Python 3.7+ you can just use asyncio.run(coroutine())

In earlier versions you have to get the event loop and run from there:

loop = asyncio.get_event_loop()
asyncio.ensure_future(coroutine())
loop.run_forever()
loop.close()
Sign up to request clarification or add additional context in comments.

2 Comments

actually this worked for me loop = get_event_loop() loop.run_until_complete(get_all_allowed_systems(app))
I wish it was that simple. In Python 3.12 I get Already running asyncio in this thread, for both suggestions.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.