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 SerializableCard
async def run(app: Mightstone):
await mightstone.enable_persistence()
total = await SerializableCard.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.to_serializable().save()
total = await SerializableCard.count()
print(f"We saved {total} cards in the database after our research")
card = await SerializableCard.find_one()
if not card:
print("Failed to read from database")
exit(0)
else:
print(f"For instance, {card.name} with uuid {card.id} is in the database")
queried = await app.scryfall.named_async(card.name)
print("I can query it directly and find it again through the named endpoint")
await queried.to_serializable().save()
print(
"As I save it, the unique key prevent it from being inserted again it will be "
"updated "
)
after_total = await SerializableCard.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 pymongo_inmemory import Mongod
from pymongo_inmemory.context import Context
from mightstone.services.scryfall import Scryfall, SerializableCard
async def run():
# client = AsyncIOMotorClient("mongodb://user:pass@host:27017")
with Mongod(Context()) as mongo_server:
client = AsyncIOMotorClient(mongo_server.connection_string)
models = [SerializableCard] # 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()
await random.to_serializable().save()
count = await SerializableCard.find().count()
print(f"I now have {count} card in my database")
asyncio.run(run())