0

我有一个烧瓶-restful 项目,它与一些自定义类接口,包含uuid.UUID用作 id 的 uuid ( ) 类型。有几个 api 端点返回与给定 id 关联的对象,由 flask 解析为UUID. 问题是,当我将它们作为 json 有效负载返回时,会出现以下异常:

UUID('…') is not JSON serializable

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

4

1 回答 1

1

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

首先,我需要创建一个自定义 json 编码器,它在处理 uuid 时会返回它们的字符串表示形式。StackOverflow在这里回答

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答案在这里

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

我希望它对某人有用!

于 2021-08-15T14:57:27.340 回答