Created
January 31, 2020 21:48
-
-
Save pjaol/e7bdc6a7213479a9c245fbb137b91f24 to your computer and use it in GitHub Desktop.
Recursively convert mongoengine object to a python object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bson.objectid import ObjectId | |
from datetime import datetime | |
from decimal import Decimal | |
from mongoengine.base.datastructures import EmbeddedDocumentList | |
def _checkTypes (ref) : | |
allowed_list = [str, ObjectId, datetime, int, float, Decimal] | |
if ref is None : | |
return True | |
for i in allowed_list : | |
if isinstance(ref, i) : | |
return True | |
return False | |
def flattenMongoDoc(doc, resultList = None): | |
result = {} | |
if isinstance(doc, EmbeddedDocumentList) : | |
if resultList == None : | |
resultList = [] | |
for i in doc : | |
resultList.append(flattenMongoDoc(i, resultList)) | |
return resultList | |
for i in doc : | |
if not isinstance(i,str ): | |
return "" | |
v = getattr(doc,i) | |
#typeof = type(v) | |
#print(typeof) | |
if _checkTypes(v) : | |
result[i] = v | |
else : | |
#print("Recursing "+ str(typeof)) | |
result[i] = flattenMongoDoc(v) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment