本文整理汇总了Python中pydantic.create_model方法的典型用法代码示例。如果您正苦于以下问题:Python pydantic.create_model方法的具体用法?Python pydantic.create_model怎么用?Python pydantic.create_model使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pydantic
的用法示例。
在下文中一共展示了pydantic.create_model方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sqlalchemy_to_pydantic
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def sqlalchemy_to_pydantic(
db_model: Type, *, exclude: Container[str] = []
) -> Type[BaseModel]:
"""
Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy
"""
mapper = inspect(db_model)
fields = {}
for attr in mapper.attrs:
if isinstance(attr, ColumnProperty):
if attr.columns:
column = attr.columns[0]
python_type = column.type.python_type
name = attr.key
if name in exclude:
continue
default = None
if column.default is None and not column.nullable:
default = ...
fields[name] = (python_type, default)
pydantic_model = create_model(
db_model.__name__, **fields # type: ignore
)
return pydantic_model
示例2: test_repeat_base_usage
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_repeat_base_usage():
class Model(BaseModel):
a: str
assert Model.__fields__.keys() == {'a'}
model = create_model('FooModel', b=1, __base__=Model)
assert Model.__fields__.keys() == {'a'}
assert model.__fields__.keys() == {'a', 'b'}
model2 = create_model('Foo2Model', c=1, __base__=Model)
assert Model.__fields__.keys() == {'a'}
assert model.__fields__.keys() == {'a', 'b'}
assert model2.__fields__.keys() == {'a', 'c'}
model3 = create_model('Foo2Model', d=1, __base__=model)
assert Model.__fields__.keys() == {'a'}
assert model.__fields__.keys() == {'a', 'b'}
assert model2.__fields__.keys() == {'a', 'c'}
assert model3.__fields__.keys() == {'a', 'b', 'd'}
示例3: fixture_model_with_path
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def fixture_model_with_path(request):
class Config:
arbitrary_types_allowed = True
ModelWithPath = create_model(
"ModelWithPath", path=(request.param, ...), __config__=Config
)
return ModelWithPath(path=request.param("/foo", "bar"))
示例4: get_pagination_model
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def get_pagination_model(display_model):
return create_pydantic_model(
f"PaginationResponse_{display_model.__name__}",
count=(int, ...),
next=(Optional[str], None),
previous=(Optional[str], None),
result=(List[display_model], ...),
__base__=BaseModel,
)
示例5: validate_args
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def validate_args(spec, location):
"""
A rough implementation of webargs using pydantic schemas. You can pass a
pydantic schema as spec or create it on the fly as follows:
@validate_args({"name": (str, None), "id": (int, None)}, location="query")
"""
if isinstance(spec, dict):
spec = create_model("", **spec)
schema = spec.schema()
props = schema.get("properties", {})
required = schema.get("required", [])
for k in props:
if k in required:
props[k]["required"] = True
props[k]["in"] = location
def decorator(func):
# Inject parameters information into the Flask-Restx apidoc attribute.
# Not really a good solution. See https://github.com/CTFd/CTFd/issues/1504
apidoc = getattr(func, "__apidoc__", {"params": {}})
apidoc["params"].update(props)
func.__apidoc__ = apidoc
@wraps(func)
def wrapper(*args, **kwargs):
data = ARG_LOCATIONS[location]()
loaded = spec(**data).dict(exclude_unset=True)
return func(*args, loaded, **kwargs)
return wrapper
return decorator
示例6: test_invalid_identifiers_signature
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [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')
示例7: test_create_model
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_create_model():
model = create_model('FooModel', foo=(str, ...), bar=123)
assert issubclass(model, BaseModel)
assert issubclass(model.__config__, BaseModel.Config)
assert model.__name__ == 'FooModel'
assert model.__fields__.keys() == {'foo', 'bar'}
assert model.__validators__ == {}
assert model.__config__.__name__ == 'Config'
示例8: test_create_model_usage
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_create_model_usage():
model = create_model('FooModel', foo=(str, ...), bar=123)
m = model(foo='hello')
assert m.foo == 'hello'
assert m.bar == 123
with pytest.raises(ValidationError):
model()
with pytest.raises(ValidationError):
model(foo='hello', bar='xxx')
示例9: test_invalid_name
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_invalid_name():
with pytest.warns(RuntimeWarning):
model = create_model('FooModel', _foo=(str, ...))
assert len(model.__fields__) == 0
示例10: test_field_wrong_tuple
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_field_wrong_tuple():
with pytest.raises(errors.ConfigError):
create_model('FooModel', foo=(1, 2, 3))
示例11: test_inheritance
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_inheritance():
class BarModel(BaseModel):
x = 1
y = 2
model = create_model('FooModel', foo=(str, ...), bar=(int, 123), __base__=BarModel)
assert model.__fields__.keys() == {'foo', 'bar', 'x', 'y'}
m = model(foo='a', x=4)
assert m.dict() == {'bar': 123, 'foo': 'a', 'x': 4, 'y': 2}
示例12: test_custom_config
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_custom_config():
class Config:
fields = {'foo': 'api-foo-field'}
model = create_model('FooModel', foo=(int, ...), __config__=Config)
assert model(**{'api-foo-field': '987'}).foo == 987
assert issubclass(model.__config__, BaseModel.Config)
with pytest.raises(ValidationError):
model(foo=654)
示例13: test_custom_config_inherits
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_custom_config_inherits():
class Config(BaseModel.Config):
fields = {'foo': 'api-foo-field'}
model = create_model('FooModel', foo=(int, ...), __config__=Config)
assert model(**{'api-foo-field': '987'}).foo == 987
assert issubclass(model.__config__, BaseModel.Config)
with pytest.raises(ValidationError):
model(foo=654)
示例14: test_custom_config_extras
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_custom_config_extras():
class Config(BaseModel.Config):
extra = Extra.forbid
model = create_model('FooModel', foo=(int, ...), __config__=Config)
assert model(foo=654)
with pytest.raises(ValidationError):
model(bar=654)
示例15: test_inheritance_validators
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import create_model [as 别名]
def test_inheritance_validators():
class BarModel(BaseModel):
@validator('a', check_fields=False)
def check_a(cls, v):
if 'foobar' not in v:
raise ValueError('"foobar" not found in a')
return v
model = create_model('FooModel', a='cake', __base__=BarModel)
assert model().a == 'cake'
assert model(a='this is foobar good').a == 'this is foobar good'
with pytest.raises(ValidationError):
model(a='something else')