Closed johnpaulett closed 10 months ago
@johnpaulett What do you think about adding native Pydantic support to this library instead?
@mdomke not opposed. I think this PR still could be independently valid if others created subclasses of ULID for whatever reason.
@mdomke thanks! If you want a PR that adds these three methods into the core python-ulid, I'm happy to do so. Just debatable if you want it in here or not.
@johnpaulett I ended up adding the Pydantic support directly to this library
@mdomke thanks!
For those that run into this error...
pydantic_core._pydantic_core.PydanticSerializationError: Unable to serialize unknown type: <class 'ulid.ULID'>
...you'll need to set a Functional Serializer (such as PlainSerializer
). You can provide additional information for your FastAPI schema using WithJsonSchema
.
from ulid import ULID as _ULID
ULID = Annotated[
_ULID,
PlainSerializer(
lambda x: f"{x}",
return_type=str,
),
WithJsonSchema(
{
"type": "string",
"examples": ["01F1Z3ZJX9NQW8J9X1ZQXZJY9H"],
},
mode="serialization",
),
]
To serialize ULID in Pydantic, I've subclassed
ulid.ULID
Currently,
MyULID.from_str("01F1Z3ZJX9NQW8J9X1ZQXZJY9A")
will returnULID
instead ofMyULID
.This PR marks the return of the classmethods as returning an instance of the subclass.
Happy to adjust if we want to try to reuse one of the existing TypeVars or reorganize where they are defined.