为了解决这个问题,我不得不把来自两个不同地方的建议放在一起:
首先,我需要创建一个自定义 json 编码器,它在处理 uuid 时会返回它们的字符串表示形式。 StackOverflow 回答here
import json
from uuid import UUID
class UUIDEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, UUID):
# if the obj is uuid, we simply return the value of uuid
return str(obj) # <- notice I'm not returning obj.hex as the original answer
return json.JSONEncoder.default(self, obj)
其次,我需要使用这个新的编码器并将其设置为用于响应的烧瓶-restful 编码器。 GitHub回答here
class MyConfig(object):
RESTFUL_JSON = {'cls': MyCustomEncoder}
app = Flask(__name__)
app.config.from_object(MyConfig)
api = Api(app)
把它放在一起:
# ?: custom json encoder to be able to fix the UUID('…') is not JSON serializable
class UUIDEncoder(json.JSONEncoder):
def default(self, obj: Any) -> Any: # pylint:disable=arguments-differ
if isinstance(obj, UUID):
return str(obj) # <- notice I'm not returning obj.hex as the original answer
return json.JSONEncoder.default(self, obj)
# ?: api configuration to switch the json encoder
class MyConfig(object):
RESTFUL_JSON = {"cls": UUIDEncoder}
app = Flask(__name__)
app.config.from_object(MyConfig)
api = Api(app)
附带说明,如果您使用的是香草flask,则过程更简单,只需直接设置您的应用程序json编码器(app.json_encoder = UUIDEncoder)
我希望它对某人有用!