当前位置: 首页>>代码示例>>Python>>正文


Python fields.Nested方法代码示例

本文整理汇总了Python中marshmallow.fields.Nested方法的典型用法代码示例。如果您正苦于以下问题:Python fields.Nested方法的具体用法?Python fields.Nested怎么用?Python fields.Nested使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在marshmallow.fields的用法示例。


在下文中一共展示了fields.Nested方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_nested_string_to_cls

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_nested_string_to_cls():
    class TestNamedNestedSchema(Schema):
        foo = fields.Integer(required=True)

    class TestSchema(Schema):
        foo2 = fields.Integer(required=True)
        nested = fields.Nested("TestNamedNestedSchema")

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    nested_def = dumped["definitions"]["TestNamedNestedSchema"]
    nested_dmp = dumped["definitions"]["TestSchema"]["properties"]["nested"]
    assert nested_dmp["type"] == "object"
    assert nested_def["properties"]["foo"]["format"] == "integer" 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:18,代码来源:test_dump.py

示例2: test_nested_descriptions

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_nested_descriptions():
    class TestNestedSchema(Schema):
        myfield = fields.String(metadata={"description": "Brown Cow"})
        yourfield = fields.Integer(required=True)

    class TestSchema(Schema):
        nested = fields.Nested(
            TestNestedSchema, metadata={"description": "Nested 1", "title": "Title1"}
        )
        yourfield_nested = fields.Integer(required=True)

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    nested_def = dumped["definitions"]["TestNestedSchema"]
    nested_dmp = dumped["definitions"]["TestSchema"]["properties"]["nested"]
    assert nested_def["properties"]["myfield"]["description"] == "Brown Cow"

    assert nested_dmp["$ref"] == "#/definitions/TestNestedSchema"
    assert nested_dmp["description"] == "Nested 1"
    assert nested_dmp["title"] == "Title1" 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:24,代码来源:test_dump.py

示例3: test_list_nested

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_list_nested():
    """Test that a list field will work with an inner nested field."""

    class InnerSchema(Schema):
        foo = fields.Integer(required=True)

    class ListSchema(Schema):
        bar = fields.List(fields.Nested(InnerSchema), required=True)

    schema = ListSchema()
    dumped = validate_and_dump(schema)

    nested_json = dumped["definitions"]["ListSchema"]["properties"]["bar"]

    assert nested_json["type"] == "array"
    assert "items" in nested_json

    item_schema = nested_json["items"]
    assert "InnerSchema" in item_schema["$ref"] 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:21,代码来源:test_dump.py

示例4: test_deep_nested

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_deep_nested():
    """Test that deep nested schemas are in definitions."""

    class InnerSchema(Schema):
        boz = fields.Integer(required=True)

    class InnerMiddleSchema(Schema):
        baz = fields.Nested(InnerSchema, required=True)

    class OuterMiddleSchema(Schema):
        bar = fields.Nested(InnerMiddleSchema, required=True)

    class OuterSchema(Schema):
        foo = fields.Nested(OuterMiddleSchema, required=True)

    schema = OuterSchema()
    dumped = validate_and_dump(schema)

    defs = dumped["definitions"]
    assert "OuterSchema" in defs
    assert "OuterMiddleSchema" in defs
    assert "InnerMiddleSchema" in defs
    assert "InnerSchema" in defs 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:25,代码来源:test_dump.py

示例5: test_respect_only_for_nested_schema

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_respect_only_for_nested_schema():
    """Should ignore fields not in 'only' metadata for nested schemas."""

    class InnerRecursiveSchema(Schema):
        id = fields.Integer(required=True)
        baz = fields.String()
        recursive = fields.Nested("InnerRecursiveSchema")

    class MiddleSchema(Schema):
        id = fields.Integer(required=True)
        bar = fields.String()
        inner = fields.Nested("InnerRecursiveSchema", only=("id", "baz"))

    class OuterSchema(Schema):
        foo2 = fields.Integer(required=True)
        nested = fields.Nested("MiddleSchema")

    schema = OuterSchema()
    dumped = validate_and_dump(schema)
    inner_props = dumped["definitions"]["InnerRecursiveSchema"]["properties"]
    assert "recursive" not in inner_props 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:23,代码来源:test_dump.py

示例6: test_respect_dotted_exclude_for_nested_schema

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_respect_dotted_exclude_for_nested_schema():
    """Should ignore dotted fields in 'exclude' metadata for nested schemas."""

    class InnerRecursiveSchema(Schema):
        id = fields.Integer(required=True)
        baz = fields.String()
        recursive = fields.Nested("InnerRecursiveSchema")

    class MiddleSchema(Schema):
        id = fields.Integer(required=True)
        bar = fields.String()
        inner = fields.Nested("InnerRecursiveSchema")

    class OuterSchema(Schema):
        foo2 = fields.Integer(required=True)
        nested = fields.Nested("MiddleSchema", exclude=("inner.recursive",))

    schema = OuterSchema()

    dumped = validate_and_dump(schema)

    inner_props = dumped["definitions"]["InnerRecursiveSchema"]["properties"]
    assert "recursive" not in inner_props 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:25,代码来源:test_dump.py

示例7: test_nested_instance

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_nested_instance():
    """Should also work with nested schema instances"""

    class TestNestedSchema(Schema):
        baz = fields.Integer()

    class TestSchema(Schema):
        foo = fields.String()
        bar = fields.Nested(TestNestedSchema())

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    nested_def = dumped["definitions"]["TestNestedSchema"]
    nested_obj = dumped["definitions"]["TestSchema"]["properties"]["bar"]

    assert "baz" in nested_def["properties"]
    assert nested_obj["$ref"] == "#/definitions/TestNestedSchema" 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:21,代码来源:test_dump.py

示例8: test_additional_properties_from_nested_meta

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_additional_properties_from_nested_meta(additional_properties_value):
    class TestNestedSchema(Schema):
        class Meta:
            additional_properties = additional_properties_value

        foo = fields.Integer()

    class TestSchema(Schema):
        nested = fields.Nested(TestNestedSchema())

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    assert (
        dumped["definitions"]["TestNestedSchema"]["additionalProperties"]
        == additional_properties_value
    ) 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:20,代码来源:test_additional_properties.py

示例9: schema

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def schema(**kwargs):
    """
    Create a schema. Mostly useful for creating single-use schemas on-the-fly.
    """
    items = list(kwargs.items())
    if len(items) != 1 or not isinstance(items[0][1], dict):
        raise RuntimeError('schema required 1 keyword argument of type dict')
    name, spec = items[0]

    schema_dict = {}
    for key, value in spec.items():
        cls, description = value if isinstance(value, tuple) else (value, None)
        required = key.endswith('*')
        key = key.rstrip('*')
        kwargs = {'required': required, 'description': description}

        if isinstance(cls, SchemaMeta):
            schema_dict[key] = Nested(cls, required=required)
        elif isinstance(cls, list) and len(cls) == 1:
            cls = cls[0]
            schema_dict[key] = List(Nested(cls), **kwargs) if isinstance(cls, SchemaMeta) else List(cls, **kwargs)
        else:
            schema_dict[key] = cls.__call__(**kwargs) if callable(cls) else cls
    return type(name, (Schema,), schema_dict) 
开发者ID:Tribler,项目名称:py-ipv8,代码行数:26,代码来源:schema.py

示例10: test_using_as_nested_schema

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_using_as_nested_schema(self):
        class SchemaWithList(m.Schema):
            items = f.List(f.Nested(MySchema))

        schema = SchemaWithList()
        result = schema.load(
            {
                "items": [
                    {"type": "Foo", "value": "hello world!"},
                    {"type": "Bar", "value": 123},
                ]
            }
        )
        assert {"items": [Foo("hello world!"), Bar(123)]} == result

        with pytest.raises(m.ValidationError) as exc_info:
            schema.load(
                {"items": [{"type": "Foo", "value": "hello world!"}, {"value": 123}]}
            )
        assert {"items": {1: {"type": [REQUIRED_ERROR]}}} == exc_info.value.messages 
开发者ID:marshmallow-code,项目名称:marshmallow-oneofschema,代码行数:22,代码来源:test_one_of_schema.py

示例11: test_using_as_nested_schema_with_many

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_using_as_nested_schema_with_many(self):
        class SchemaWithMany(m.Schema):
            items = f.Nested(MySchema, many=True)

        schema = SchemaWithMany()
        result = schema.load(
            {
                "items": [
                    {"type": "Foo", "value": "hello world!"},
                    {"type": "Bar", "value": 123},
                ]
            }
        )
        assert {"items": [Foo("hello world!"), Bar(123)]} == result

        with pytest.raises(m.ValidationError) as exc_info:
            schema.load(
                {"items": [{"type": "Foo", "value": "hello world!"}, {"value": 123}]}
            )
        assert {"items": {1: {"type": [REQUIRED_ERROR]}}} == exc_info.value.messages 
开发者ID:marshmallow-code,项目名称:marshmallow-oneofschema,代码行数:22,代码来源:test_one_of_schema.py

示例12: create_app

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def create_app(self):
        app = Flask(__name__)
        Rebar().init_app(app=app)

        class NestedSchema(validation.RequestSchema):
            baz = fields.List(fields.Integer())

        class Schema(validation.RequestSchema):
            foo = fields.Integer(required=True)
            bar = fields.Email()
            nested = fields.Nested(NestedSchema)

        @app.route("/stuffs", methods=["POST"])
        def json_body_handler():
            data = get_json_body_params_or_400(schema=Schema)
            return response(data)

        return app 
开发者ID:plangrid,项目名称:flask-rebar,代码行数:20,代码来源:test_errors.py

示例13: __init__

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def __init__(self, allow_extra):
        class LocationSchema(Schema):
            latitude = fields.Float(allow_none=True)
            longitude = fields.Float(allow_none=True)

        class SkillSchema(Schema):
            subject = fields.Str(required=True)
            subject_id = fields.Integer(required=True)
            category = fields.Str(required=True)
            qual_level = fields.Str(required=True)
            qual_level_id = fields.Integer(required=True)
            qual_level_ranking = fields.Float(default=0)

        class Model(Schema):
            id = fields.Integer(required=True)
            client_name = fields.Str(validate=validate.Length(max=255), required=True)
            sort_index = fields.Float(required=True)
            # client_email = fields.Email()
            client_phone = fields.Str(validate=validate.Length(max=255), allow_none=True)

            location = fields.Nested(LocationSchema)

            contractor = fields.Integer(validate=validate.Range(min=0), allow_none=True)
            upstream_http_referrer = fields.Str(validate=validate.Length(max=1023), allow_none=True)
            grecaptcha_response = fields.Str(validate=validate.Length(min=20, max=1000), required=True)
            last_updated = fields.DateTime(allow_none=True)
            skills = fields.Nested(SkillSchema, many=True)

        self.allow_extra = allow_extra  # unused
        self.schema = Model() 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:32,代码来源:test_marshmallow.py

示例14: makePaginationSchema

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def makePaginationSchema(itemsCls, field_cls=fields.Nested):
    return type("{}Paging".format(itemsCls.__class__.__name__),
                (BasePaging, ), dict(items=field_cls(itemsCls, many=True))) 
开发者ID:beavyHQ,项目名称:beavy,代码行数:5,代码来源:paging_schema.py

示例15: test_nested_recursive

# 需要导入模块: from marshmallow import fields [as 别名]
# 或者: from marshmallow.fields import Nested [as 别名]
def test_nested_recursive():
    """A self-referential schema should not cause an infinite recurse."""

    class RecursiveSchema(Schema):
        foo = fields.Integer(required=True)
        children = fields.Nested("RecursiveSchema", many=True)

    schema = RecursiveSchema()

    dumped = validate_and_dump(schema)

    props = dumped["definitions"]["RecursiveSchema"]["properties"]
    assert "RecursiveSchema" in props["children"]["items"]["$ref"] 
开发者ID:fuhrysteve,项目名称:marshmallow-jsonschema,代码行数:15,代码来源:test_dump.py


注:本文中的marshmallow.fields.Nested方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。