Skip to content

Commit f0396f3

Browse files
committed
add pydantic support
1 parent 465e413 commit f0396f3

File tree

4 files changed

+103
-2
lines changed

4 files changed

+103
-2
lines changed

datauri/__init__.py

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,17 @@ def text(self):
102102
return self.data.decode(self.charset)
103103

104104
@property
105-
def _parse(self):
105+
def is_valid(self):
106106
match = _DATA_URI_RE.match(self)
107107
if not match:
108+
return False
109+
return True
110+
111+
@property
112+
def _parse(self):
113+
if self.is_valid is False:
108114
raise InvalidDataURI("Not a valid data URI: %r" % self)
115+
match = _DATA_URI_RE.match(self)
109116
mimetype = match.group("mimetype") or None
110117
name = match.group("name") or None
111118
charset = match.group("charset") or None
@@ -118,3 +125,30 @@ def _parse(self):
118125
data = unquote(match.group("data"))
119126

120127
return mimetype, name, charset, bool(match.group("base64")), data
128+
129+
# Pydantic methods
130+
@classmethod
131+
def __get_validators__(cls):
132+
# one or more validators may be yielded which will be called in the
133+
# order to validate the input, each validator will receive as an input
134+
# the value returned from the previous validator
135+
yield cls.validate
136+
137+
@classmethod
138+
def validate(cls, v):
139+
if not isinstance(v, str):
140+
raise TypeError('string required')
141+
142+
m = cls(v)
143+
if not m.is_valid:
144+
raise ValueError('invalid data-uri format')
145+
return m
146+
147+
@classmethod
148+
def __modify_schema__(cls, field_schema):
149+
# __modify_schema__ should mutate the dict it receives in place,
150+
# the returned value will be ignored
151+
field_schema.update(
152+
pattern=DATA_URI_REGEX,
153+
examples=["data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"],
154+
)

poetry.lock

Lines changed: 54 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ six = "^1.16.0"
1414
[tool.poetry.group.dev.dependencies]
1515
coveralls = "^3.3.1"
1616
pytest = "^7.3.1"
17+
pydantic = "^1.10.8"
1718

1819
[build-system]
1920
requires = ["poetry-core"]

tests/test_pydantic.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import pytest
2+
3+
from datauri import DataURI
4+
pydantic = pytest.importorskip("pydantic")
5+
6+
7+
def test_pydantic():
8+
class Model(pydantic.BaseModel):
9+
content: DataURI
10+
11+
t = "data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu"
12+
instance = Model(content=t)
13+
assert isinstance(instance.content, DataURI)

0 commit comments

Comments
 (0)