本文整理汇总了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"]
示例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
示例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')
"""
)
示例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")
示例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'
示例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
示例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
示例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'],
}
示例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
示例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"] == []
示例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") == []
示例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'
示例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')
示例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')
示例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)