参考:flask jsonify() 兼容Numpy类型_我是一只程序⚪的博客-CSDN博客
from flask.json.provider import DefaultJSONProvider
from flask import Flask as _Flask
class FlaskJSONProvider(DefaultJSONProvider):
@classmethod
def default(cls, o):
"""
功能:重写default方法
特殊说明:
2、参考官方文档:
https://dormousehole.readthedocs.io/en/latest/api.html?highlight=json_provider_class#flask.Flask.json_provider_class
https://dormousehole.readthedocs.io/en/latest/api.html?highlight=json_provider_class#flask.json.provider.DefaultJSONProvider
"""
if hasattr(o, "keys") and hasattr(o, "__getitem__"):
"""
1、【自定义】兼容对象转换成dict的方案!
"""
return dict(o)
try:
"""
1、兼容官方默认的方案
"""
return super().default(o)
except TypeError:
raise ServerException(f'Object of type __class {o.__class__.__name__}__ is not JSON serializable')
class Flask(_Flask):
"""
选择自定义的JSONProvider编码器
"""
json_provider_class = FlaskJSONProvider