當前位置: 首頁>>代碼示例>>Python>>正文


Python pydantic.Field方法代碼示例

本文整理匯總了Python中pydantic.Field方法的典型用法代碼示例。如果您正苦於以下問題:Python pydantic.Field方法的具體用法?Python pydantic.Field怎麽用?Python pydantic.Field使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pydantic的用法示例。


在下文中一共展示了pydantic.Field方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_fields_items

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_fields_items(self):
        class Foo(CCIDictModel):
            bar: str = None
            fields_ = Field([], alias="fields")

        class Document(CCIDictModel):
            __root__: Foo

        # JSON is YAML. Strange but true.
        foo = Document.parse_from_yaml(StringIO("{bar: 'blah'}"))
        assert type(foo) == Foo
        assert foo["fields"] == []

        foo = Document.parse_from_yaml(StringIO("{bar: 'blah', fields: [1,2]}"))
        assert foo["fields"] == [1, 2]

        foo["fields"] = ["a", "b"]
        assert foo["fields"] == ["a", "b"] 
開發者ID:SFDO-Tooling,項目名稱:CumulusCI,代碼行數:20,代碼來源:test_model_parser.py

示例2: test_del

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_del(self):
        class Foo(CCIDictModel):
            bar: str = None
            fields_ = Field([], alias="fields")

        x = Foo.parse_obj({"bar": "q"})
        assert x["bar"] == x.bar == "q"
        assert "bar" in x
        del x["bar"]
        assert "bar" not in x
        assert x.get("bar") is None

        assert x["fields"] == x.fields == []
        assert "fields" in x
        del x["fields"]
        assert "fields" not in x
        assert x.get("fields") is None 
開發者ID:SFDO-Tooling,項目名稱:CumulusCI,代碼行數:19,代碼來源:test_model_parser.py

示例3: test_forward_ref_with_field

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_forward_ref_with_field(create_module):
    create_module(
        """
from typing import List
from pydantic import BaseModel, Field
from pydantic.typing import ForwardRef

Foo = ForwardRef('Foo')

try:
    class Foo(BaseModel):
        c: List[Foo] = Field(..., gt=0)
except ValueError:
    pass
else:
    raise AssertionError('error not raised')
    """
    ) 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:20,代碼來源:test_forward_ref.py

示例4: test_custom_init_signature

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_custom_init_signature():
    class MyModel(BaseModel):
        id: int
        name: str = 'John Doe'
        f__: str = Field(..., alias='foo')

        class Config:
            extra = Extra.allow

        def __init__(self, id: int = 1, bar=2, *, baz: Any, **data):
            super().__init__(id=id, **data)
            self.bar = bar
            self.baz = baz

    sig = signature(MyModel)
    assert _equals(
        map(str, sig.parameters.values()),
        ('id: int = 1', 'bar=2', 'baz: Any', "name: str = 'John Doe'", 'foo: str', '**data'),
    )

    assert _equals(str(sig), "(id: int = 1, bar=2, *, baz: Any, name: str = 'John Doe', foo: str, **data) -> None") 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:23,代碼來源:test_model_signature.py

示例5: test_env_inheritance_field

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_env_inheritance_field(env):
    class SettingsParent(BaseSettings):
        foobar: str = Field('parent default', env='foobar_env')

    class SettingsChild(SettingsParent):
        foobar: str = 'child default'

    assert SettingsParent().foobar == 'parent default'
    assert SettingsParent(foobar='abc').foobar == 'abc'

    assert SettingsChild().foobar == 'child default'
    assert SettingsChild(foobar='abc').foobar == 'abc'
    env.set('foobar_env', 'env value')
    assert SettingsParent().foobar == 'env value'
    assert SettingsParent(foobar='abc').foobar == 'abc'
    assert SettingsChild().foobar == 'child default'
    assert SettingsChild(foobar='abc').foobar == 'abc' 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:19,代碼來源:test_settings.py

示例6: test_default_factory_called_once

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_default_factory_called_once():
    """It should call only once the given factory by default"""

    class Seq:
        def __init__(self):
            self.v = 0

        def __call__(self):
            self.v += 1
            return self.v

    class MyModel(BaseModel):
        id: int = Field(default_factory=Seq())

    m1 = MyModel()
    assert m1.id == 1
    m2 = MyModel()
    assert m2.id == 2
    assert m1.id == 1 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:21,代碼來源:test_main.py

示例7: test_default_factory_called_once_2

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_default_factory_called_once_2():
    """It should call only once the given factory by default"""

    v = 0

    def factory():
        nonlocal v
        v += 1
        return v

    class MyModel(BaseModel):
        id: int = Field(default_factory=factory)

    m1 = MyModel()
    assert m1.id == 1
    m2 = MyModel()
    assert m2.id == 2 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:19,代碼來源:test_main.py

示例8: test_schema_class

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_schema_class():
    class Model(BaseModel):
        foo: int = Field(4, title='Foo is Great')
        bar: str = Field(..., description='this description of bar')

    with pytest.raises(ValidationError):
        Model()

    m = Model(bar=123)
    assert m.dict() == {'foo': 4, 'bar': '123'}

    assert Model.schema() == {
        'type': 'object',
        'title': 'Model',
        'properties': {
            'foo': {'type': 'integer', 'title': 'Foo is Great', 'default': 4},
            'bar': {'type': 'string', 'title': 'Bar', 'description': 'this description of bar'},
        },
        'required': ['bar'],
    } 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:22,代碼來源:test_schema.py

示例9: doc_fixture

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def doc_fixture():
    class Nest(BaseModel):
        """A nested model"""

        n: float = 56

    class X(BaseModel):
        """A Pydantic model made up of many, many different combinations of ways of mapping types in Pydantic"""

        x: int
        y: str = Field(...)
        n: Nest
        n2: Nest = Field(Nest(), description="A detailed description")
        z: float = 5
        z2: float = None
        z3: Optional[float]
        z4: Optional[float] = Field(5, description="Some number I just made up")
        z5: Optional[Union[float, int]]
        z6: Optional[List[int]]
        l: List[int]
        l2: List[Union[int, str]]
        t: Tuple[str, int]
        t2: Tuple[List[int]]
        t3: Tuple[Any]
        d: Dict[str, Any]
        dlu: Dict[Union[int, str], List[Union[int, str, float]]] = Field(..., description="this is complicated")
        dlu2: Dict[Any, List[Union[int, str, float]]]
        dlu3: Dict[str, Any]
        si: int = Field(..., description="A level of constraint", gt=0)
        sf: float = Field(None, description="Optional Constrained Number", le=100.3)

    yield X 
開發者ID:MolSSI,項目名稱:QCElemental,代碼行數:34,代碼來源:test_utils.py

示例10: test_getitem_missing

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_getitem_missing(self):
        class Foo(CCIDictModel):
            bar: str = None
            fields_ = Field([], alias="fields")

        x = Foo.parse_obj({})
        assert x
        with pytest.raises(IndexError):
            x["foo"]

        assert "bar" in x
        assert "fields" in x
        assert x["fields"] == [] 
開發者ID:SFDO-Tooling,項目名稱:CumulusCI,代碼行數:15,代碼來源:test_model_parser.py

示例11: test_get

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_get(self):
        class Foo(CCIDictModel):
            bar: str = None
            fields_ = Field([], alias="fields")

        x = Foo.parse_obj({"bar": "q"})
        assert x.get("bar") == x.bar == x["bar"] == "q"
        assert x.get("xyzzy", 0) == 0
        assert x.get("xyzzy") is None
        assert x.get("fields") == [] 
開發者ID:SFDO-Tooling,項目名稱:CumulusCI,代碼行數:12,代碼來源:test_model_parser.py

示例12: test_custom_schema

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_custom_schema():
    T = TypeVar('T')

    class MyModel(GenericModel, Generic[T]):
        a: int = Field(1, description='Custom')

    schema = MyModel[int].schema()
    assert schema['properties']['a'].get('description') == 'Custom' 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:10,代碼來源:test_generics.py

示例13: test_model_signature

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_model_signature():
    class Model(BaseModel):
        a: float = Field(..., title='A')
        b = Field(10)

    sig = signature(Model)
    assert sig != signature(BaseModel)
    assert _equals(map(str, sig.parameters.values()), ('a: float', 'b: int = 10'))
    assert _equals(str(sig), '(*, a: float, b: int = 10) -> None') 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:11,代碼來源:test_model_signature.py

示例14: test_invalid_identifiers_signature

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_invalid_identifiers_signature():
    model = create_model(
        'Model', **{'123 invalid identifier!': Field(123, alias='valid_identifier'), '!': Field(0, alias='yeah')}
    )
    assert _equals(str(signature(model)), '(*, valid_identifier: int = 123, yeah: int = 0) -> None')
    model = create_model('Model', **{'123 invalid identifier!': 123, '!': Field(0, alias='yeah')})
    assert _equals(str(signature(model)), '(*, yeah: int = 0, **extra_data: Any) -> None') 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:9,代碼來源:test_model_signature.py

示例15: test_const_differentiates_union

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import Field [as 別名]
def test_const_differentiates_union():
    class SubModelA(BaseModel):
        key: str = Field('A', const=True)
        foo: int

    class SubModelB(BaseModel):
        key: str = Field('B', const=True)
        foo: int

    class Model(BaseModel):
        a: Union[SubModelA, SubModelB]

    m = Model.parse_obj({'a': {'key': 'B', 'foo': 3}})
    assert isinstance(m.a, SubModelB) 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:16,代碼來源:test_parse.py


注:本文中的pydantic.Field方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。