odmantic icon indicating copy to clipboard operation
odmantic copied to clipboard

Trying to use db_engine.configure_database([User])

Open StandinKP opened this issue 1 year ago • 1 comments

Trying to use db_engine.configure_database([User]) but as we need to await it, it cannot be directly run without any async function declared and called. Do you need to create a factory for this?

This is my code:

from config.settings import DB
from logger import logging
from odmantic import AIOEngine
from motor.motor_asyncio import AsyncIOMotorClient
from odmantic.session import AIOSession

from models.user import User

db_client = AsyncIOMotorClient(
    f"mongodb://{quote_plus(DB.user)}:{quote_plus(DB.pass_)}@{DB.host}:{DB.port}"
    if (DB.user and DB.pass_)
    else f"mongodb://{DB.host}:{DB.port}"
)
db_engine = AIOEngine(database=DB.name, client=db_client)

await db_engine.configure_database([User])

StandinKP avatar Dec 19 '23 18:12 StandinKP

Managed to use it with below code:

loop = asyncio.get_event_loop()
if loop and loop.is_running():
    tsk = loop.create_task(db_engine.configure_database([User]))
    tsk.add_done_callback(
        lambda t: print(f"Task done with result={t.result()}  << return val of main()")
    )

But is this the correct approach or any other way is supposed to be used?

StandinKP avatar Dec 19 '23 18:12 StandinKP