Worked on #13 and #4. There are some caching issues left, though. Introduced abstract class Cacheable. Replaced async_pymongo with pymongo

This commit is contained in:
2025-05-06 02:54:30 +02:00
parent 9d562e2e9d
commit 86c75d06fa
22 changed files with 412 additions and 137 deletions

View File

@@ -6,6 +6,7 @@ from bson import ObjectId
from libbot.cache.classes import Cache
from pymongo.results import InsertOneResult
from classes.abstract import Cacheable
from classes.errors import GuildNotFoundError
from modules.database import col_guilds
from modules.utils import get_logger, restore_from_cache
@@ -14,7 +15,7 @@ logger: Logger = get_logger(__name__)
@dataclass
class PycordGuild:
class PycordGuild(Cacheable):
"""Dataclass of DB entry of a guild"""
__slots__ = (
@@ -57,7 +58,7 @@ class PycordGuild:
cached_entry: Dict[str, Any] | None = restore_from_cache(cls.__short_name__, guild_id, cache=cache)
if cached_entry is not None:
return cls(**cached_entry)
return cls(**cls._entry_from_cache(cached_entry))
db_entry = await cls.__collection__.find_one({"id": guild_id})
@@ -72,7 +73,7 @@ class PycordGuild:
db_entry["_id"] = insert_result.inserted_id
if cache is not None:
cache.set_json(f"{cls.__short_name__}_{guild_id}", db_entry)
cache.set_json(f"{cls.__short_name__}_{guild_id}", cls._entry_to_cache(db_entry))
return cls(**db_entry)
@@ -115,10 +116,10 @@ class PycordGuild:
if cache is None:
return
user_dict: Dict[str, Any] = self.to_dict()
object_dict: Dict[str, Any] = self.to_dict(json_compatible=True)
if user_dict is not None:
cache.set_json(self._get_cache_key(), user_dict)
if object_dict is not None:
cache.set_json(self._get_cache_key(), object_dict)
else:
self._delete_cache(cache)
@@ -128,6 +129,22 @@ class PycordGuild:
cache.delete(self._get_cache_key())
@staticmethod
def _entry_to_cache(db_entry: Dict[str, Any]) -> Dict[str, Any]:
cache_entry: Dict[str, Any] = db_entry.copy()
cache_entry["_id"] = str(cache_entry["_id"])
return cache_entry
@staticmethod
def _entry_from_cache(cache_entry: Dict[str, Any]) -> Dict[str, Any]:
db_entry: Dict[str, Any] = cache_entry.copy()
db_entry["_id"] = ObjectId(db_entry["_id"])
return db_entry
def to_dict(self, json_compatible: bool = False) -> Dict[str, Any]:
"""Convert the object to a JSON representation.