Skip to content

Commit

Permalink
improve docs and examples
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed Sep 21, 2023
1 parent e0a4fbf commit 9d7fce5
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/api/base_model.md
Expand Up @@ -22,6 +22,7 @@ Pydantic models are simply classes which inherit from `BaseModel` and define fie
- model_rebuild
- model_validate
- model_validate_json
- model_validate_strings
- copy

::: pydantic.create_model
Expand Down
2 changes: 1 addition & 1 deletion pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 30 additions & 1 deletion pydantic/main.py
Expand Up @@ -538,7 +538,12 @@ def model_validate_strings(
strict: bool | None = None,
context: dict[str, Any] | None = None,
) -> Model:
"""Validate the given object contains string data against the Pydantic model.
"""Validate the given object against the Pydantic model assuming the data originates from strings.
This is useful when validating data like query parameters, HTTP headers, or environment variables
where the input data is always a string; in particular where you want to be strict about
the input format while still allowing coercion of the string to the expected type,
see [pydantic#7065](https://github.com/pydantic/pydantic/issues/7065).
Args:
obj: The object contains string data to validate.
Expand All @@ -547,6 +552,30 @@ def model_validate_strings(
Returns:
The validated Pydantic model.
Example:
```py
from datetime import date
from pydantic import BaseModel, ValidationError
class MyModel(BaseModel):
dt: date
# because we're using `validate_strings`,
# the string input to a `date` field is valid, even in strict mode
m = MyModel.model_validate_strings({'dt': '2021-01-01'}, strict=True)
print(m)
#> dt=datetime.date(2021, 1, 1)
try:
# however a datetime is not valid in strict mode
m = MyModel.model_validate_strings(
{'dt': '2021-01-01T00:00:00'}, strict=True
)
except ValidationError:
pass
```
"""
# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
__tracebackhide__ = True
Expand Down
9 changes: 9 additions & 0 deletions pydantic/type_adapter.py
Expand Up @@ -231,6 +231,15 @@ def validate_strings(self, __obj: Any, *, strict: bool | None = None, context: d
Returns:
The validated object.
Example:
```py
from pydantic import TypeAdapter
ta = TypeAdapter(int)
print(ta.validate_strings('123', strict=True))
#> 123
```
"""
return self.validator.validate_strings(__obj, strict=strict, context=context)

Expand Down

0 comments on commit 9d7fce5

Please sign in to comment.