當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。