python - 棉花糖嵌套 post_load 对象创建

标签 python flash sqlalchemy marshmallow

我正在开发一个处理嵌套数据结构的 API。当尝试使用 marshmallow 时,我无法想出一个解决方案来创建嵌套模型实例并引用其父实例。 Marshmallow 的 post_load 按顺序从子对象到父对象而不是父对象到子对象。有没有办法扭转这种情况?我想从序列化父级开始并将其作为上下文传递给子级。

var_test = {
    "id": 1,
    "name": "dad a",
    "children_a": [
        {
            "id": 2,
            "name": "child 1 - 2",
            "grand_children_a": [
                {
                    "id": 2,
                    "name": "child 1 - 2",
                }
            ]
        },
        {
            "id": 3,
            "name": "child 2 - 2",
        }
    ]
}

class ParentA(Schema):
    id = fields.Integer()
    name = fields.String()
    children_a = fields.Nested('ChildrenA', many=True)
    @post_load()
    def pl_handler(self, data):
        # create Parent A
        return data

class ChildrenA(Schema):
    id = fields.Integer()
    name = fields.String()
    grand_children_a = fields.Nested('GrandchildrenA', many=True)
    @post_load()
    def pl_handler(self, data):
        # create child of Parent A
        return data

class GrandchildrenA(Schema):
    id = fields.Integer()
    name = fields.String()
    @post_load()
    def pl_handler(self, data):
        # create child of ChildrenA
        return "grand child string"

var_s = ParentA()
var_s.load(var_test)

最佳答案

我认为,您不需要 post_load,因为没有要从此模式反序列化的类,所以只需删除它,它就可以工作。 如果您打算将其反序列化并保存到任何类,则需要在 post_load 装饰器中返回,例如:

from marshmallow import Schema, fields, INCLUDE, post_load

class Author:
    def __init__(self, name, age):
        self.name = name
        self.age = age


class Book:
    def __init__(self, title, description, author):
        self.title = title
        self.description = description
        self.author = author

class AuthorSchema(Schema):
    name = fields.Str()
    age = fields.Int()

    @post_load
    def load_author(self, data, **kwargs):
        return Author(**data)


class BookSchema(Schema):
    title = fields.Str()
    description = fields.Str()
    author = fields.Nested(AuthorSchema)

    @post_load
    def load_book(self, data, **kwargs):
        return Book(**data)





data = {
    "title": "Test Book",
    "description": "A book Test",
    "author": {"name": "Vivek", "age": 35},
}


book = BookSchema(unknown=INCLUDE).load(data )
print(book)
print(book.author)
print(book.author.name)

关于python - 棉花糖嵌套 post_load 对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41267475/

相关文章:

python - 常规 Python for 循环中的 If 子句

apache-flex - 使用 services-config.xml 和未知的 context.root 编译 Flex 应用程序

python - 通过 SqlAlchemy 中的关联对象实现多对多、自引用、非对称关系(twitter 模型)

python - 如何在 SQLALchemy 中执行左连接?

python - Flask-SQLAlchemy 多态关联

python - 如何将 ddbmock 与 dynamodb-mapper 一起使用?

python - SQLAlchemy 中需要多少个 Base 或 MetaData 实例?

python - 如何在 Tkinter 中识别不可打印的 KeyPress 事件

actionscript-3 - AS3:如何访问和控制外部SWF中的嵌入式声音?

json - 解析Flash JSON响应(Delphi/TWebbrowser)