art049 / odmantic

Sync and Async ODM (Object Document Mapper) for MongoDB based on python type hints
http://art049.github.io/odmantic
ISC License
1.06k stars 92 forks source link

Trying to use db_engine.configure_database([User]) #392

Open StandinKP opened 9 months ago

StandinKP commented 9 months ago

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 commented 9 months ago

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?