Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Samuel Colvin <s@muelcolvin.com>
- Loading branch information
1 parent
f36040a
commit 63337fb
Showing
5 changed files
with
93 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
When generating field schema, pass optional `field` argument (of type | ||
`pydantic.fields.ModelField`) to `__modify_schema__()` if present |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# output-json | ||
from typing import Optional | ||
|
||
from pydantic import BaseModel, Field | ||
from pydantic.fields import ModelField | ||
|
||
|
||
class RestrictedAlphabetStr(str): | ||
@classmethod | ||
def __get_validators__(cls): | ||
yield cls.validate | ||
|
||
@classmethod | ||
def validate(cls, value, field: ModelField): | ||
alphabet = field.field_info.extra['alphabet'] | ||
if any(c not in alphabet for c in value): | ||
raise ValueError(f'{value!r} is not restricted to {alphabet!r}') | ||
return cls(value) | ||
|
||
@classmethod | ||
def __modify_schema__(cls, field_schema, field: Optional[ModelField]): | ||
if field: | ||
alphabet = field.field_info.extra['alphabet'] | ||
field_schema['examples'] = [c * 3 for c in alphabet] | ||
|
||
|
||
class MyModel(BaseModel): | ||
value: RestrictedAlphabetStr = Field(alphabet='ABC') | ||
|
||
|
||
print(MyModel.schema_json(indent=2)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters