我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用flask.json.JSONEncoder()。
def default(self, o): if isinstance(o, datetime.datetime): if o.tzinfo: # eg: '2015-09-25T23:14:42.588601+00:00' return o.isoformat('T') else: # No timezone present - assume UTC. # eg: '2015-09-25T23:14:42.588601Z' return o.isoformat('T') + 'Z' if isinstance(o, datetime.date): return o.isoformat() if isinstance(o, Decimal): return float(o) return json.JSONEncoder.default(self, o)
def default(self, o): if isinstance(o, date): return o.isoformat() return json.JSONEncoder.default(self, o)
def render(self): data = { 'status': { 'code': self.code, 'message': self.message }, 'data': self.data } return json.dumps(data, cls=JSONEncoder, ensure_ascii=False)
def default(self, o): if isinstance(o, _LazyString): return str(o) return JSONEncoder.default(self, o)
def render(self, data, media_type, **options): # Requested indentation may be set in the Accept header. data = self.pre_render(data, media_type, **options) try: indent = max(min(int(media_type.params['indent']), 8), 0) except (KeyError, ValueError, TypeError): indent = None # Indent may be set explicitly, eg when rendered by the browsable API. indent = options.get('indent', indent) if six.PY2: # pragma: no cover return json.dumps(data, cls=JSONEncoder, ensure_ascii=False, indent=indent, encoding=self.charset) else: # pragma: no cover return json.dumps(data, cls=JSONEncoder, ensure_ascii=False, indent=indent)
def _make_encoder(superclass): class MongoEngineJSONEncoder(superclass): """ A JSONEncoder which provides serialization of MongoEngine documents and queryset objects. """ def default(self, obj): if isinstance(obj, BaseDocument): return json_util._json_convert(obj.to_mongo()) elif isinstance(obj, QuerySet): return json_util._json_convert(obj.as_pymongo()) return superclass.default(self, obj) return MongoEngineJSONEncoder
def override_json_encoder(app): """ A function to dynamically create a new MongoEngineJSONEncoder class based upon a custom base class. This function allows us to combine MongoEngine serialization with any changes to Flask's JSONEncoder which a user may have made prior to calling init_app. NOTE: This does not cover situations where users override an instance's json_encoder after calling init_app. """ app.json_encoder = _make_encoder(app.json_encoder)