How to use the pydantic.create_model function in pydantic

To help you get started, we’ve selected a few pydantic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github samuelcolvin / pydantic / tests / test_create_model.py View on Github external
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)
github samuelcolvin / pydantic / tests / test_create_model.py View on Github external
def test_config_and_base():
    with pytest.raises(errors.ConfigError):
        create_model('FooModel', __config__=BaseModel.Config, __base__=BaseModel)
github samuelcolvin / pydantic / tests / test_create_model.py View on Github external
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')
github samuelcolvin / pydantic / tests / test_create_model.py View on Github external
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'}
github tiangolo / fastapi / fastapi / utils.py View on Github external
def create_cloned_field(field: ModelField) -> ModelField:
    original_type = field.type_
    if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"):
        original_type = original_type.__pydantic_model__  # type: ignore
    use_type = original_type
    if lenient_issubclass(original_type, BaseModel):
        original_type = cast(Type[BaseModel], original_type)
        use_type = create_model(
            original_type.__name__, __config__=original_type.__config__
        )
        for f in original_type.__fields__.values():
            use_type.__fields__[f.name] = f
        use_type.__validators__ = original_type.__validators__
    if PYDANTIC_1:
        new_field = ModelField(
            name=field.name,
            type_=use_type,
            class_validators={},
            default=None,
            required=False,
            model_config=BaseConfig,
            field_info=FieldInfo(None),
        )
    else:  # pragma: nocover
github rafalp / Misago / misago / graphql / mutations / editthreadtitle.py View on Github external
async def create_input_model(context: GraphQLContext) -> EditThreadTitleInputModel:
    return create_model(
        "EditThreadTitleInputModel",
        thread=(PositiveInt, ...),
        title=(threadtitlestr(context["settings"]), ...),
    )
github rafalp / Misago / misago / graphql / mutations / postreply.py View on Github external
async def create_input_model(context: GraphQLContext) -> PostReplyInputModel:
    return create_model(
        "PostReplyInputModel",
        thread=(PositiveInt, ...),
        body=(constr(strip_whitespace=True), ...),
    )
github Gr1N / aioapi / aioapi / inspect / inspector.py View on Github external
_, body_type = body_pair
            request_mapping["body"] = body_type

        for k, mapping in (("path", path_mapping), ("query", query_mapping)):
            if not mapping:
                continue

            request_mapping[k] = (
                create_model(
                    k.title(), **{k: v for k, v in mapping.items()}  # type: ignore
                ),
                Required,
            )

        request_type = (
            create_model("Request", **request_mapping)  # type: ignore
            if request_mapping
            else None
        )

        return HandlerMeta(
            name=self._handler_name,
            components_mapping=components_mapping or None,
            request_type=request_type,
            request_body_pair=body_pair,
            request_path_mapping=path_mapping or None,
            request_query_mapping=query_mapping or None,
        )
github awslabs / gluon-ts / src / gluonts / core / component.py View on Github external
if param.default != inspect.Parameter.empty
                else ...,
            )
            for param in init_params.values()
            if param.name != "self"
            and param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
        }

        if base_model is None:
            PydanticModel = create_model(
                model_name=f"{init_clsnme}Model",
                __config__=BaseValidatedInitializerModel.Config,
                **init_fields,
            )
        else:
            PydanticModel = create_model(
                model_name=f"{init_clsnme}Model",
                __base__=base_model,
                **init_fields,
            )

        def validated_repr(self) -> str:
            return dump_code(self)

        def validated_getnewargs_ex(self):
            return (), self.__init_args__

        @functools.wraps(init)
        def init_wrapper(*args, **kwargs):
            self, *args = args

            nmargs = {
github rafalp / Misago / misago / graphql / mutations / editpost.py View on Github external
async def create_input_model(context: GraphQLContext) -> EditPostInputModel:
    return create_model(
        "EditPostInputModel",
        post=(PositiveInt, ...),
        body=(constr(strip_whitespace=True), ...),
    )