【问题标题】:Serialize UUID objects in flask-restful在 flask-restful 中序列化 UUID 对象
【发布时间】:2021-10-17 21:46:23
【问题描述】:

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

UUID('…') is not JSON serializable

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

【问题讨论】:

    标签: python flask flask-restful


    【解决方案1】:

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

    首先,我需要创建一个自定义 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

    我希望它对某人有用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      相关资源
      最近更新 更多