Last active
August 9, 2021 17:57
-
-
Save corydolphin/11005158 to your computer and use it in GitHub Desktop.
Fix: TypeError: ObjectId is not JSON serializable: A Flask JSONEncoder for Mongoengine documents. Specifically useful for use with Flask-Mongoengine.
This file contains 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 flask import Flask | |
from flask.json import JSONEncoder | |
from bson import json_util | |
from mongoengine.base import BaseDocument | |
from mongoengine.queryset.base import BaseQuerySet | |
class MongoEngineJSONEncoder(JSONEncoder): | |
def default(self,obj): | |
if isinstance(obj,BaseDocument): | |
return json_util._json_convert(obj.to_mongo()) | |
elif isinstance(obj,BaseQuerySet): | |
return json_util._json_convert(obj.as_pymongo()) | |
return JSONEncoder.default(self, obj) | |
''' | |
To use: | |
from mongoengine_jsonencoder import MongoEngineJsonEncoder | |
app = Flask(__name__) | |
app.json_encoder = MongoEngineJSONEncoder | |
Now Flask's jsonify works for Mongoengine querysets, and documents. | |
''' |
anaplopes
commented
Jul 17, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment