2023-11-29 00:39:14 -08:00
|
|
|
import base64
|
2024-09-10 12:52:57 -07:00
|
|
|
from typing import Any, Type
|
2023-11-29 00:39:14 -08:00
|
|
|
|
|
|
|
from pydantic import GetCoreSchemaHandler
|
2024-09-10 12:52:57 -07:00
|
|
|
from pydantic_core import core_schema
|
2023-11-29 00:39:14 -08:00
|
|
|
|
|
|
|
|
2024-09-10 12:52:57 -07:00
|
|
|
class Base64Data(bytes):
|
|
|
|
@classmethod
|
|
|
|
def __get_pydantic_core_schema__(
|
|
|
|
cls, source: Type[Any], handler: GetCoreSchemaHandler
|
|
|
|
) -> core_schema.CoreSchema:
|
|
|
|
return core_schema.no_info_after_validator_function(
|
|
|
|
cls.validate,
|
|
|
|
core_schema.union_schema(
|
|
|
|
[
|
|
|
|
core_schema.str_schema(),
|
|
|
|
core_schema.bytes_schema(),
|
|
|
|
]
|
|
|
|
),
|
|
|
|
serialization=core_schema.plain_serializer_function_ser_schema(
|
|
|
|
cls.serialize
|
|
|
|
),
|
|
|
|
)
|
2023-11-29 00:39:14 -08:00
|
|
|
|
2024-09-10 12:52:57 -07:00
|
|
|
@classmethod
|
|
|
|
def validate(cls, v):
|
|
|
|
return base64.urlsafe_b64decode(v.strip("=") + "===")
|
2023-11-29 00:39:14 -08:00
|
|
|
|
|
|
|
@classmethod
|
2024-09-10 12:52:57 -07:00
|
|
|
def serialize(cls, v: "Base64Data") -> bytes:
|
|
|
|
return v
|