Skip to content

Commit c573ff1

Browse files
authored
Merge pull request #18 from mperesson/fix-pydantic-json-schema-serialization
2 parents 873ea84 + 0d39557 commit c573ff1

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

datauri/__init__.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -188,13 +188,16 @@ def validate(
188188
def __get_pydantic_json_schema__(
189189
cls, core_schema: MutableMapping[str, Any], handler: Any
190190
) -> Any:
191-
core_schema.update(
192-
pattern=DATA_URI_REGEX,
193-
examples=[
194-
"data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"
195-
],
196-
)
197-
return core_schema
191+
json_schema = handler(core_schema)
192+
json_schema = handler.resolve_ref_schema(json_schema)
193+
json_schema['examples'] = [
194+
"data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"
195+
]
196+
json_schema['pattern'] = DATA_URI_REGEX
197+
json_schema['type'] = 'string'
198+
json_schema['title'] = 'DataURI'
199+
200+
return json_schema
198201

199202
@classmethod
200203
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:

tests/test_pydantic.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import json
2+
13
import pytest
24

35
from datauri import DataURI
@@ -37,3 +39,19 @@ class Model(pydantic.BaseModel):
3739
'aGUgbGF6eSBkb2cu"}'
3840
)
3941
assert instance.model_dump() == {"content": DataURI(t)}
42+
43+
44+
@pytest.mark.skipif(
45+
pydantic.__version__.rsplit(".", 3)[0] < "2", reason="pydantic v2 required"
46+
)
47+
def test_pydantic_v2_json_schema():
48+
class Model(pydantic.BaseModel):
49+
content: DataURI
50+
51+
schema = Model.model_json_schema(schema_generator=pydantic.json_schema.GenerateJsonSchema)
52+
schema_json = json.dumps(schema)
53+
val = '{"properties": {"content": {"examples": ["data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"], "pattern": "data:(?P<mimetype>[\\\w]+\\\/[\\\w\\\-\\\+\\\.]+)?(?:\\\;name\\\=(?P<name>[\\\w\\\.\\\-%!*\'~\\\(\\\)]+))?(?:\\\;charset\\\=(?P<charset>[\\\w\\\-\\\+\\\.]+))?(?P<base64>\\\;base64)?,(?P<data>.*)", "title": "DataURI", "type": "string"}}, "required": ["content"], "title": "Model", "type": "object"}'
54+
assert (
55+
schema_json
56+
== val
57+
)

0 commit comments

Comments
 (0)