24
24
# POSSIBILITY OF SUCH DAMAGE.
25
25
26
26
27
- __all__ = ("BSONObjectIdConverter" , "JSONEncoder " )
27
+ __all__ = ("BSONObjectIdConverter" , "BSONProvider " )
28
28
29
- from bson import json_util , SON
29
+ from bson import json_util
30
30
from bson .errors import InvalidId
31
31
from bson .objectid import ObjectId
32
32
from flask import abort
33
- from json import JSONEncoder
34
- from six import iteritems , string_types
33
+ from flask .json .provider import JSONProvider
35
34
from werkzeug .routing import BaseConverter
36
35
import pymongo
37
36
@@ -84,7 +83,7 @@ def to_url(self, value):
84
83
return str (value )
85
84
86
85
87
- class JSONEncoder ( JSONEncoder ):
86
+ class BSONProvider ( JSONProvider ):
88
87
89
88
"""A JSON encoder that uses :mod:`bson.json_util` for MongoDB documents.
90
89
@@ -121,35 +120,22 @@ def json_route(cart_id):
121
120
122
121
"""
123
122
124
- def __init__ (self , json_options , * args , ** kwargs ):
123
+ def __init__ (self , json_options , app ):
125
124
if json_options is None :
126
125
json_options = DEFAULT_JSON_OPTIONS
127
126
if json_options is not None :
128
127
self ._default_kwargs = {"json_options" : json_options }
129
128
else :
130
129
self ._default_kwargs = {}
131
130
132
- super (JSONEncoder , self ).__init__ (* args , ** kwargs )
131
+ super ().__init__ (app )
133
132
134
- def default (self , obj ):
133
+ def dumps (self , obj ):
135
134
"""Serialize MongoDB object types using :mod:`bson.json_util`.
135
+ """
136
+ return json_util .dumps (obj )
136
137
137
- Falls back to Flask's default JSON serialization for all other types.
138
-
139
- This may raise ``TypeError`` for object types not recognized.
140
-
141
- .. versionadded:: 2.4.0
142
-
138
+ def loads (self , str_obj ):
139
+ """Deserialize MongoDB object types using :mod:`bson.json_util`.
143
140
"""
144
- if hasattr (obj , "iteritems" ) or hasattr (obj , "items" ):
145
- return SON ((k , self .default (v )) for k , v in iteritems (obj ))
146
- elif hasattr (obj , "__iter__" ) and not isinstance (obj , string_types ):
147
- return [self .default (v ) for v in obj ]
148
- else :
149
- try :
150
- return json_util .default (obj , ** self ._default_kwargs )
151
- except TypeError :
152
- # PyMongo couldn't convert into a serializable object, and
153
- # the Flask default JSONEncoder won't; so we return the
154
- # object itself and let stdlib json handle it if possible
155
- return obj
141
+ return json_util .loads (str_obj )
0 commit comments