beanie icon indicating copy to clipboard operation
beanie copied to clipboard

[BUG] init_beanie working slow

Open owais3901 opened this issue 7 months ago • 1 comments

Profiler of the code

2.956 example test.py:29 ├─ 2.392 init_beanie beanie/odm/utils/init.py:725 │ [2 frames hidden] beanie │ 2.389 [await] beanie/odm/utils/init.py ├─ 0.366 AsyncIOMotorClient.init motor/core.py:130 │ [31 frames hidden] motor, pymongo, dns, httpcore, anyio,... └─ 0.197 Test.wrapper beanie/odm/actions.py:222 [5 frames hidden] beanie

Python Code :

import asyncio from typing import Optional

from motor.motor_asyncio import AsyncIOMotorClient from pydantic import BaseModel import time from pyinstrument import Profiler

from beanie import Document, Indexed, init_beanie

class Category(BaseModel): name: str description: str

class Test(Document): name: str # You can use normal types just like in pydantic description: Optional[str] = None price: Indexed(float) # You can also specify that a field should correspond to an index category: Category # You can include pydantic models as well

This is an asynchronous example, so we will access it from an async function

async def example(): prev = time.time() start_profile = Profiler() start_profile.start() # Beanie uses Motor async client under the hood client = AsyncIOMotorClient(MONGO_URI)

# Initialize beanie with the Product document class
await init_beanie(database=client.Test, document_models=[Test])
print(time.time()-prev)
chocolate = Category(name="Chocolate", description="A preparation of roasted and ground cacao seeds.")
# Beanie documents work just like pydantic models
tonybar = Test(name="Tony's", price=5.95, category=chocolate)
# And can be inserted into the database

print(await tonybar.insert())
start_profile.stop()
start_profile.print()

if name == "main": asyncio.run(example())

owais3901 avatar Jul 23 '24 09:07 owais3901