【问题标题】:How to deserialize a bjson structure to an marshmallow schema如何将 bjson 结构反序列化为棉花糖模式
【发布时间】:2016-08-12 23:38:57
【问题描述】:

我正在尝试将 bjson 结构转换为棉花糖库中的模式。

下面是棉花糖架构:

class GeneSchema(Schema):
"""description of class"""

   id_entrez = fields.Integer(required = True, error_messages={'required': "The 'id_entrez' field is requeired."})
   symbol = fields.String()

   @validates('id_entrez')
   def validate_id_entrez(self, data):
       if data <= 0:
          raise ValidationError("The 'id_entrez' field must be greater than zero.")

下面是bjson将被转换为schema:

[{"symbol": "VAMP4", "_id": {"$oid": "57ae3b175a945932fcbdf41d"}, "id_entrez": 8674}, {"symbol": "CCT5", "_id": {"$oid": "57ae3b175a945932fcbdf41e"}, "id_entrez": 22948}]

请注意,bjson 的“_id”为 ObjectId - “$oid”。这是因为使用mongodb查询的结果。

请问,有谁知道为什么不能正确地从 bjson 转换为 marshmallow 模式?

谢谢大家!

【问题讨论】:

    标签: python mongodb marshmallow


    【解决方案1】:

    您仍然可以使用您的模式来解析 MongoDB 输出,只需忽略额外的“_id”字段。另一方面,如果您确实想解析该“_id”,只需在您的架构中添加额外的非必需字段。

    【讨论】:

      【解决方案2】:

      我不知道这个问题是否仍然有效,但我想展示我的解决方案,如何将 ObjectId 推送到 Marshmallow 架构:

      我只是使用pre processing method pre_load 将 ObjectId 转换为字符串:

      @pre_load
      def convert_objectid(self, in_data, **kwargs):
          if "_id" in in_data:
              in_data["_id"] = str(in_data["_id"])
          return in_data
      

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-01
        • 2021-12-14
        相关资源
        最近更新 更多