Persistence
Mightstone uses Beanie as storage backend. This implies that you need to setup beanie backend before any instance of MightstoneDocument
is created.
beanie.exceptions.CollectionWasNotInitialized
exception are raised as soon as a MightstoneDocument
class is instanced before init_beanie
is called. Please check Beanie Documentation to learn more.
Automatic setup (recommended)
If you access to Mightstone content through the a Mightstone()
this is done automatically.
import asyncio
import os
import tempfile
from mightstone.app import Mightstone
from mightstone.services.scryfall import Card
async def run(app: Mightstone):
total = await Card.count()
print(f"There are currently {total} cards in the database")
async for res in app.scryfall.search_async("c:b cmc=2 o:destroy"):
await res.save()
total = await Card.count()
print(f"We saved {total} cards in the database after our research")
card = await Card.find_one()
print(f"For instance, {card.name} with uuid {card.id} is in the database")
queried = await app.scryfall.named_async(card.name)
print(f"I can query it directly and find it again through the named endpoint")
await queried.save()
print(
"As I save it, the unique key prevent it from being inserted again it will be "
"updated "
)
after_total = await Card.count()
print(f"There are still {after_total} in the database.")
with tempfile.TemporaryDirectory() as directory:
os.environ["mightstone_db_uri"] = directory
mightstone = Mightstone()
asyncio.run(run(mightstone))
This approach is recommended since our beanie implementation may evolved drastically.
Manual setup
If you wish to use base object, you’ll need to initialize beanie.
import asyncio
from beanie import init_beanie
# from motor.motor_asyncio import AsyncIOMotorClient
from beanita import Client
from mightstone.core import get_documents
from mightstone.services.scryfall import Card, Scryfall
async def run():
# client = AsyncIOMotorClient("mongodb://user:pass@host:27017")
client = Client()
models = [Card] # or mightstone.core.get_documents()
# Initialize beanie with the Product document class and a database
await init_beanie(database=client.my_database, document_models=models)
scryfall = Scryfall()
random = await scryfall.random_async()
await random.save()
count = await Card.find().count()
print(f"I now have {count} card in my database")
asyncio.run(run())