@@ -16,6 +16,23 @@ def use_json_provider() -> bool:
1616 return int (version [0 ]) > 2 or (int (version [0 ]) == 2 and int (version [1 ]) > 1 )
1717
1818
19+ # noinspection PyProtectedMember
20+ def _convert_mongo_objects (obj ):
21+ """Convert objects, related to Mongo database to JSON."""
22+ converted = None
23+ if isinstance (obj , BaseDocument ):
24+ converted = json_util ._json_convert (obj .to_mongo ())
25+ elif isinstance (obj , QuerySet ):
26+ converted = json_util ._json_convert (obj .as_pymongo ())
27+ elif isinstance (obj , CommandCursor ):
28+ converted = json_util ._json_convert (obj )
29+ elif isinstance (obj , DBRef ):
30+ converted = obj .id
31+ elif isinstance (obj , ObjectId ):
32+ converted = obj .__str__ ()
33+ return converted
34+
35+
1936def _make_encoder (superclass ):
2037 """Extend Flask JSON Encoder 'default' method with support of Mongo objects."""
2138 import warnings
@@ -35,20 +52,14 @@ class MongoEngineJSONEncoder(superclass):
3552 documents and queryset objects.
3653 """
3754
38- # noinspection PyProtectedMember, DuplicatedCode
3955 def default (self , obj ):
4056 """Extend JSONEncoder default method, with Mongo objects."""
41- if isinstance (obj , BaseDocument ):
42- return json_util ._json_convert (obj .to_mongo ())
43- elif isinstance (obj , QuerySet ):
44- return json_util ._json_convert (obj .as_pymongo ())
45- elif isinstance (obj , CommandCursor ):
46- return json_util ._json_convert (obj )
47- elif isinstance (obj , DBRef ):
48- return obj .id
49- elif isinstance (obj , ObjectId ):
50- return obj .__str__ ()
51- return superclass .default (self , obj )
57+ if isinstance (
58+ obj ,
59+ (BaseDocument , QuerySet , CommandCursor , DBRef , ObjectId ),
60+ ):
61+ return _convert_mongo_objects (obj )
62+ return super ().default (obj )
5263
5364 return MongoEngineJSONEncoder
5465
@@ -59,20 +70,14 @@ def _update_json_provider(superclass):
5970 class MongoEngineJSONProvider (superclass ):
6071 """A JSON Provider update for Flask 2.2.0+"""
6172
62- # noinspection PyProtectedMember, DuplicatedCode
6373 @staticmethod
6474 def default (obj ):
6575 """Extend JSONProvider default static method, with Mongo objects."""
66- if isinstance (obj , BaseDocument ):
67- return json_util ._json_convert (obj .to_mongo ())
68- elif isinstance (obj , QuerySet ):
69- return json_util ._json_convert (obj .as_pymongo ())
70- elif isinstance (obj , CommandCursor ):
71- return json_util ._json_convert (obj )
72- elif isinstance (obj , DBRef ):
73- return obj .id
74- elif isinstance (obj , ObjectId ):
75- return obj .__str__ ()
76+ if isinstance (
77+ obj ,
78+ (BaseDocument , QuerySet , CommandCursor , DBRef , ObjectId ),
79+ ):
80+ return _convert_mongo_objects (obj )
7681 return super ().default (obj )
7782
7883 return MongoEngineJSONProvider
0 commit comments