Skip to content

Commit

Permalink
feat: documentation and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
PascalDR committed Dec 20, 2023
1 parent 7a6c1ea commit 3c084a5
Showing 1 changed file with 46 additions and 15 deletions.
61 changes: 46 additions & 15 deletions pyeudiw/storage/mongo_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,40 @@
import pymongo

from pyeudiw.storage.base_cache import BaseCache, RetrieveStatus
from pymongo.collection import Collection
from pymongo.mongo_client import MongoClient
from pymongo.database import Database


class MongoCache(BaseCache):
"""
MongoDB cache implementation.
"""

def __init__(self, conf: dict, url: str, connection_params: dict = None) -> None:
"""
Create a MongoCache istance.
:param conf: the configuration of the cache.
:type conf: dict
:param url: the url of the MongoDB server.
:type url: str
:param connection_params: the connection parameters.
:type connection_params: dict, optional
"""
super().__init__()

self.storage_conf = conf
self.url = url
self.connection_params = connection_params

self.client = None
self.db = None

def _connect(self):
if not self.client or not self.client.server_info():
self.client = pymongo.MongoClient(
self.url, **self.connection_params)
self.db = getattr(self.client, self.storage_conf["db_name"])
self.collection = getattr(self.db, "cache_storage")
self.client: MongoClient = None
self.db: Database = None
self.collection: Collection = None

def _gen_cache_object(self, object_name: str, data: str):
return {
"object_name": object_name,
"data": data,
"creation_date": datetime.now().isoformat()
}
def close(self) -> None:
self._connect()
self.client.close()

def try_retrieve(self, object_name: str, on_not_found: Callable[[], str]) -> tuple[dict, RetrieveStatus]:
self._connect()
Expand Down Expand Up @@ -72,3 +80,26 @@ def set(self, data: dict) -> dict:
self._connect()

return self.collection.insert_one(data)

def _connect(self) -> None:
if not self.client or not self.client.server_info():
self.client = pymongo.MongoClient(
self.url, **self.connection_params)
self.db = getattr(self.client, self.storage_conf["db_name"])
self.collection = getattr(self.db, "cache_storage")

def _gen_cache_object(self, object_name: str, data: str) -> dict:
"""
Helper function to generate a cache object.
:param object_name: the name of the object.
:type object_name: str
:param data: the data to store.
:type data: str
"""

return {
"object_name": object_name,
"data": data,
"creation_date": datetime.now().isoformat()
}

0 comments on commit 3c084a5

Please sign in to comment.