序列化 flask 中的 UUID 对象-restful

Serialize UUID objects in flask-restful

我有一个 flask-restful 项目,它与一些自定义 类 接口,包含用作 ID 的 uuid (uuid.UUID) 类型。有几个 api 端点,其中 return 与给定 id 关联的对象,由 flask 解析为 UUID。问题是,当我 return 它们作为 json 有效载荷时,我得到以下异常:

UUID('…') is not JSON serializable

我希望将这些 uuid 表示为最终用户的字符串,使过程无缝(用户可以采用 returned uuid 并将其用于他的下一个 api 请求)。

为了解决这个问题,我不得不把来自两个不同地方的建议放在一起:

首先,我需要创建一个自定义 json 编码器,在处理 uuid 时,returns 它们的字符串表示。 Whosebug 回答 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)

其次,我需要使用这个新编码器并将其设置为用于响应的 flask-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)

附带说明一下,如果您使用的是 vanilla flask,过程更简单,只需直接设置您的应用程序 json 编码器 (app.json_encoder = UUIDEncoder)

希望对大家有用!