diff --git a/changes/1767-PrettyWood.md b/changes/1767-PrettyWood.md new file mode 100644 index 0000000000..7262d7eca7 --- /dev/null +++ b/changes/1767-PrettyWood.md @@ -0,0 +1 @@ +add basic support of Pattern type in schema generation diff --git a/docs/build/schema_mapping.py b/docs/build/schema_mapping.py index 0972c4b9a3..f9731c0a00 100755 --- a/docs/build/schema_mapping.py +++ b/docs/build/schema_mapping.py @@ -145,6 +145,13 @@ 'JSON Schema Validation', '' ], + [ + 'Pattern', + 'string', + {'format': 'regex'}, + 'JSON Schema Validation', + '' + ], [ 'bytes', 'string', diff --git a/pydantic/schema.py b/pydantic/schema.py index 27c66b2bd3..15b5066785 100644 --- a/pydantic/schema.py +++ b/pydantic/schema.py @@ -14,6 +14,7 @@ Iterable, List, Optional, + Pattern, Sequence, Set, Tuple, @@ -618,6 +619,7 @@ def field_singleton_sub_fields_schema( (IPv6Interface, {'type': 'string', 'format': 'ipv6interface'}), (IPv4Address, {'type': 'string', 'format': 'ipv4'}), (IPv6Address, {'type': 'string', 'format': 'ipv6'}), + (Pattern, {'type': 'string', 'format': 'regex'}), (str, {'type': 'string'}), (bytes, {'type': 'string', 'format': 'binary'}), (bool, {'type': 'boolean'}), @@ -643,7 +645,8 @@ def add_field_type_to_schema(field_type: Any, schema: Dict[str, Any]) -> None: and then modifies the given `schema` with the information from that type. """ for type_, t_schema in field_class_to_schema: - if issubclass(field_type, type_): + # Fallback for `typing.Pattern` as it is not a valid class + if lenient_issubclass(field_type, type_) or field_type is type_ is Pattern: schema.update(t_schema) break diff --git a/tests/test_types.py b/tests/test_types.py index 084b9d071a..6752c60722 100644 --- a/tests/test_types.py +++ b/tests/test_types.py @@ -2055,6 +2055,13 @@ class Foobar(BaseModel): f2 = Foobar(pattern=p) assert f2.pattern is p + assert Foobar.schema() == { + 'type': 'object', + 'title': 'Foobar', + 'properties': {'pattern': {'type': 'string', 'format': 'regex', 'title': 'Pattern'}}, + 'required': ['pattern'], + } + def test_pattern_error(): class Foobar(BaseModel):