Skip to content

Instantly share code, notes, and snippets.

@cr0hn
Created October 4, 2022 07:39
Show Gist options
  • Save cr0hn/5053ca0d5a904c637a822aef00219314 to your computer and use it in GitHub Desktop.
Save cr0hn/5053ca0d5a904c637a822aef00219314 to your computer and use it in GitHub Desktop.
Serializable Python class interfaces for MongoDB
class MetaMongo(type):
def __call__(cls, *args, **kwargs):
if "_id" in kwargs:
_id = kwargs.pop("_id")
o = super().__call__(*args, **kwargs)
return o
class Serializable(metaclass=MetaMongo):
def _clean_dict_(self,
data = None,
clean_or_raw: str = "clean") -> dict:
# DICT
if type(data) is dict:
ret = {}
for x, y in data.items():
if x.startswith("raw") and clean_or_raw == "clean":
continue
ret[x] = self._clean_dict_(y, clean_or_raw=clean_or_raw)
return ret
# LIST
elif type(data) is list:
ret = []
for d in data:
ret.append(self._clean_dict_(d, clean_or_raw=clean_or_raw))
return ret
elif hasattr(data, "clean_dict"):
return data.clean_dict(clean_or_raw=clean_or_raw)
elif isinstance(data, Enum):
return data.value
else:
if hasattr(data, "serialize"):
return data.decode()
return data
def clean_dict(self,
clean_or_raw: str = "clean") -> dict:
"""removes fields 'raw' from content"""
return self._clean_dict_(self.__dict__, clean_or_raw=clean_or_raw)
def raw_dict(self) -> dict:
"""Dumps all content to valid json file"""
return self.clean_dict(clean_or_raw="raw")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment