棉花糖序列化与父字段嵌套



对不起,如果以前提出过,我实际上找不到解决方案或类似的问题(也许使用错误的单词(。

我正在更新从我们不控制的客户端接收数据的现有烧瓶API(无法更改JSON数据格式(,使用Marshmallow和Peewee。

数据格式是这样的:

{
    "site_id": "0102931",
    "update_date": "2018/02/11-09:33:23",
    "updated_by": "chan1",
    "crc": "a82131cf232ff120aaf00001293f",
    "data": [{"num": 1,
              "id": "09213/12312/1",
              "chain": "chain2",
              "operator": "0000122",
              "op_name": "Fred",
              "oid": "12092109300293"
             },
             {"num": 2,
              "id": "09213/12312/2",
              "chain": "chain1",
              "operator": "0000021",
              "op_name": "Melissa",
              "oid": "8883390393"
             }]           
}

我们对主块中的任何内容都不感兴趣,但是site_id(必须将其复制到列表中的每个对象(中,以创建模型并存储数据。

这是Peeewee中的模型:

class production_item(db.Model):
   site_id = TextField(null=False)
   id_prod = TextField(null=False)
   num = SmallIntegerField(null=False)
   chain = TextField(null=False)
   operator = TextField(null=False)
   operator_name = TextField(null=True)
   order_id = TextField(null=False)

这是棉花糖模式:

class prodItemSchema(Schema):
    num=String(required=True)
    id=String(required=True)
    chain=String(required=True)
    operator=String(required=True)
    op_name=String(required=False, allow_none=True)
    oid=String(required=False, allow_none=True)

我找不到使用load((方法和Proditemschema的post-Load/Post-Load装饰器从主结构中传递site-ID的方法,因此无法创建模型。另外,我想让棉花糖为我验证整个结构,而不是像现在在代码中所做的那样在资源和模式之间进行两部分。

,但是在文档中找不到这样做的方法,这是可能的吗?

在棉花糖中,可以通过在父方案上使用pre_dump装饰器来设置上下文,然后在序列化之前将值从父方案传递给其子女。一旦设置了上下文,就可以使用函数字段从父级获取值。

class Parent(Schema):
    id = fields.String(required=True)
    data = fields.Nested('Child', many=True)
    @pre_dump
    def set_context(self, parent, **kwargs):
        self.context['site_id'] = parent['id']
        return data
class Child(Schema):
    site_id = fields.Function(inherit_from_parent)
def inherit_from_parent(child, context):
    child['site_id'] = context['site_id']
    return child

最新更新