Skip to content

Types

plateforme.core.types.binaries

This module provides utilities for managing binary types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

Binary module-attribute

Binary = Annotated[bytes, ...]

The binary proxy.

StrictBinary module-attribute

StrictBinary = Annotated[str, ...]

A binary that must be validated strictly.

BinaryFactory

Bases: BaseTypeFactory[bytes]

A binary type factory.

It extends the built-in bytes class with additional validation and schema methods.

plateforme.core.types.datetimes

This module provides utilities for managing datetime types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

Date module-attribute

Date = Annotated[date, ...]

The date proxy.

PastDate module-attribute

PastDate = Annotated[date, ...]

A date that must be in the past.

FutureDate module-attribute

FutureDate = Annotated[date, ...]

A date that must be in the future.

StrictDate module-attribute

StrictDate = Annotated[date, ...]

A date that must be validated strictly.

DateTime module-attribute

DateTime = Annotated[datetime, ...]

The date time proxy.

PastDateTime module-attribute

PastDateTime = Annotated[datetime, ...]

A date time that must be in the past.

FutureDateTime module-attribute

FutureDateTime = Annotated[datetime, ...]

A date time that must be in the future.

AwareDateTime module-attribute

AwareDateTime = Annotated[datetime, ...]

A date time that must be timezone aware.

NaiveDateTime module-attribute

NaiveDateTime = Annotated[datetime, ...]

A date time that must be timezone naive.

StrictDateTime module-attribute

StrictDateTime = Annotated[datetime, ...]

A date time that must be validated strictly.

Time module-attribute

Time = Annotated[time, ...]

The time proxy.

StrictTime module-attribute

StrictTime = Annotated[time, ...]

A time that must be validated strictly.

TimeDelta module-attribute

TimeDelta = Annotated[timedelta, ...]

The time delta proxy.

StrictTimeDelta module-attribute

StrictTimeDelta = Annotated[timedelta, ...]

A time delta that must be validated strictly.

DateFactory

Bases: BaseTypeFactory[date]

A date type factory.

It extends the built-in datetime.date class with additional validation and schema methods.

DateTimeFactory

Bases: BaseTypeFactory[datetime]

A date time type factory.

It extends the built-in datetime.datetime class with additional validation and schema methods.

TimeFactory

Bases: BaseTypeFactory[time]

A time type factory.

It extends the built-in datetime.time class with additional validation and schema methods.

TimeDeltaFactory

Bases: BaseTypeFactory[timedelta]

A time delta type factory.

It extends the built-in datetime.timedelta class with additional validation and schema methods.

plateforme.core.types.enums

This module provides utilities for managing enum types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

Enum module-attribute

Enum = Annotated[Enum, ...]

The enum proxy.

StrictEnum module-attribute

StrictEnum = Annotated[Enum, ...]

An enum that must be validated strictly.

EnumFactory

Bases: BaseTypeFactory[Enum]

An enum type factory.

It extends the built-in enum.Enum class with additional validation and schema methods.

plateforme.core.types.json

This module provides utilities for managing JSON type within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

Json

Bases: BaseType

A special type wrapper which loads JSON before parsing.

The Json data type makes Pydantic first load a raw JSON string before validating the loaded data into the parametrized type:

When the model is dumped using model_dump or model_dump_json, the dumped value will be the result of validation, not the original JSON string. However, the argument round_trip=True can be used to get the original JSON string back.

validate classmethod

validate(
    __value: Any, info: ValidationInfo | None = None
) -> Self

Validate value and return a new instance of the type.

Parameters:

Name Type Description Default
__value Any

Value to validate.

required
info ValidationInfo | None

Addition information to pass to the validator. Defaults to None.

None

Returns:

Type Description
Self

A type initialized with validated value.

Examples:

>>> class MyType(BaseType, int):
...     @classmethod
...     def validate(cls, value: Any) -> Self:
...         if value < 0:
...             raise ValueError('Value must be positive.')
...         return cls(value)
>>> MyType(1)
1
>>> MyType(-1)
ValueError: Value must be positive.
Note

Override and add validation logic here, if necessary. The validation is performed after the schema validation. For more complex logic, you may want to override the __get_pydantic_core_schema__ and __get_pydantic_json_schema__ methods directly.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/base.py
@classmethod
def validate(
    cls, __value: Any, info: ValidationInfo | None = None
) -> Self:
    """Validate value and return a new instance of the type.

    Args:
        __value: Value to validate.
        info: Addition information to pass to the validator.
            Defaults to ``None``.

    Returns:
        A type initialized with validated `value`.

    Examples:
        >>> class MyType(BaseType, int):
        ...     @classmethod
        ...     def validate(cls, value: Any) -> Self:
        ...         if value < 0:
        ...             raise ValueError('Value must be positive.')
        ...         return cls(value)
        >>> MyType(1)
        1
        >>> MyType(-1)
        ValueError: Value must be positive.

    Note:
        Override and add validation logic here, if necessary. The
        validation is performed after the schema validation. For more
        complex logic, you may want to override the
        `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`
        methods directly.
    """
    return cls(__value)

serialize classmethod

serialize(
    __value: Self, info: SerializationInfo | None = None
) -> Any

Return the serialized instance of the type.

Parameters:

Name Type Description Default
__value Self

Value to serialize.

required
info SerializationInfo | None

Additional information to pass to the serializer. Defaults to None.

None

Returns:

Type Description
Any

A serialized instance.

Examples:

>>> class MyType(BaseType, int):
...     @classmethod
...     def serialize(cls, value: Self) -> str:
...         return f"Serialized {self!r}"
Note

Override and add serialization logic here, if necessary. The serialization to be invoked is set up in the schema. For more complex logic, you may want to override the __get_pydantic_core_schema__ and __get_pydantic_json_schema__ methods directly.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/base.py
@classmethod
def serialize(
    cls, __value: Self, info: SerializationInfo | None = None
) -> Any:
    """Return the serialized instance of the type.

    Args:
        __value: Value to serialize.
        info: Additional information to pass to the serializer.
            Defaults to ``None``.

    Returns:
        A serialized instance.

    Examples:
        >>> class MyType(BaseType, int):
        ...     @classmethod
        ...     def serialize(cls, value: Self) -> str:
        ...         return f"Serialized {self!r}"

    Note:
        Override and add serialization logic here, if necessary. The
        serialization to be invoked is set up in the schema. For more
        complex logic, you may want to override the
        `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`
        methods directly.
    """
    if info and info.mode == 'json':
        return __value.__str__()
    return __value

plateforme.core.types.networks

This module provides utilities for managing network types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

DEFAULT_DRIVERS module-attribute

DEFAULT_DRIVERS = {
    "oracle": "oracledb",
    "postgresql": "asyncpg",
    "mariadb": "asyncmy",
    "mssql": "aioodbc",
    "mysql": "asyncmy",
    "sqlite": "aiosqlite",
}

The default database drivers for the supported database engines.

IPvAddressFactoryAlias module-attribute

IPvAddressFactoryAlias = Union[
    IPv4Address | IPv6Address | PydanticIPvAnyAddress
]

A type alias for the IP address factory type.

IPvAnyAddress module-attribute

IPvAnyAddress = Annotated[PydanticIPvAnyAddress, ...]

The IP address proxy.

IPv4Address module-attribute

IPv4Address = Annotated[IPv4Address, ...]

An IPv4 address proxy.

IPv6Address module-attribute

IPv6Address = Annotated[IPv6Address, ...]

An IPv6 address proxy.

IPvInterfaceFactoryAlias module-attribute

IPvInterfaceFactoryAlias = Union[
    IPv4Interface | IPv6Interface | PydanticIPvAnyInterface
]

A type alias for the IP interface factory type.

IPvAnyInterface module-attribute

IPvAnyInterface = Annotated[PydanticIPvAnyInterface, ...]

The IP interface proxy.

IPv4Interface module-attribute

IPv4Interface = Annotated[IPv4Interface, ...]

An IPv4 interface proxy.

IPv6Interface module-attribute

IPv6Interface = Annotated[IPv6Interface, ...]

An IPv6 interface proxy.

IPvNetworkFactoryAlias module-attribute

IPvNetworkFactoryAlias = Union[
    IPv4Network | IPv6Network | PydanticIPvAnyNetwork
]

A type alias for the IP network factory type.

IPvAnyNetwork module-attribute

IPvAnyNetwork = Annotated[PydanticIPvAnyNetwork, ...]

The IP network proxy.

IPv4Network module-attribute

IPv4Network = Annotated[IPv4Network, ...]

An IPv4 network proxy.

IPv6Network module-attribute

IPv6Network = Annotated[IPv6Network, ...]

An IPv6 network proxy.

AnyUrl module-attribute

AnyUrl = Annotated[PydanticUrl, ...]

The URL proxy.

AnyHttpUrl module-attribute

AnyHttpUrl = Annotated[PydanticUrl, ...]

A URL that must implement the HTTP scheme.

HttpUrl module-attribute

HttpUrl = Annotated[PydanticUrl, ...]

A URL that must implement the HTTP scheme with 2083 max length.

FileUrl module-attribute

FileUrl = Annotated[PydanticUrl, ...]

A URL that must implement the file scheme.

AmqpDsn module-attribute

AmqpDsn = Annotated[PydanticUrl, ...]

An AMQP DSN URL.

CockroachDsn module-attribute

CockroachDsn = Annotated[PydanticUrl, ...]

A CockroachDB DSN URL.

KafkaDsn module-attribute

KafkaDsn = Annotated[PydanticUrl, ...]

A Kafka DSN URL.

MariaDBDsn module-attribute

MariaDBDsn = Annotated[PydanticUrl, ...]

A MariaDB DSN URL.

MySQLDsn module-attribute

MySQLDsn = Annotated[PydanticUrl, ...]

A MySQL DSN URL.

OracleDsn module-attribute

OracleDsn = Annotated[PydanticUrl, ...]

An Oracle DSN URL.

RedisDsn module-attribute

RedisDsn = Annotated[PydanticUrl, ...]

A Redis DSN URL.

SQLiteDsn module-attribute

SQLiteDsn = Annotated[PydanticUrl, ...]

A SQLite DSN URL.

SQLServerDsn module-attribute

SQLServerDsn = Annotated[PydanticUrl, ...]

A SQL Server DSN URL.

AnyMultiHostUrl module-attribute

AnyMultiHostUrl = Annotated[PydanticMultiHostUrl, ...]

The multi host URL proxy.

MongoDsn module-attribute

A MongoDB DSN URL.

NatsDsn module-attribute

A NATS DSN URL.

PostgresDsn module-attribute

PostgresDsn = Annotated[PydanticMultiHostUrl, ...]

A PostgreSQL DSN URL.

UrlConstraints dataclass

UrlConstraints(
    max_length: int | None = None,
    allowed_schemes: list[str] | None = None,
    host_required: bool | None = None,
    default_host: str | None = None,
    default_port: int | None = None,
    default_path: str | None = None,
)

Bases: PydanticMetadata

Url constraints.

Attributes:

Name Type Description
max_length int | None

The maximum length of the url. Defaults to None.

allowed_schemes list[str] | None

The allowed schemes. Defaults to None.

host_required bool | None

Whether the host is required. Defaults to None.

default_host str | None

The default host. Defaults to None.

default_port int | None

The default port. Defaults to None.

default_path str | None

The default path. Defaults to None.

Email

Bases: BaseType

A plain email address type.

It validates an email address as specified by RFC 5322.

Examples:

>>> from plateforme import BaseModel
... from plateforme.types import Email
>>> class User(BaseModel):
...     email: Email
>>> user = User(email='jane.bloggs@example.com')
>>> print(user.email)
jane.bloggs@example.com

serialize classmethod

serialize(
    __value: Self, info: SerializationInfo | None = None
) -> Any

Return the serialized instance of the type.

Parameters:

Name Type Description Default
__value Self

Value to serialize.

required
info SerializationInfo | None

Additional information to pass to the serializer. Defaults to None.

None

Returns:

Type Description
Any

A serialized instance.

Examples:

>>> class MyType(BaseType, int):
...     @classmethod
...     def serialize(cls, value: Self) -> str:
...         return f"Serialized {self!r}"
Note

Override and add serialization logic here, if necessary. The serialization to be invoked is set up in the schema. For more complex logic, you may want to override the __get_pydantic_core_schema__ and __get_pydantic_json_schema__ methods directly.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/base.py
@classmethod
def serialize(
    cls, __value: Self, info: SerializationInfo | None = None
) -> Any:
    """Return the serialized instance of the type.

    Args:
        __value: Value to serialize.
        info: Additional information to pass to the serializer.
            Defaults to ``None``.

    Returns:
        A serialized instance.

    Examples:
        >>> class MyType(BaseType, int):
        ...     @classmethod
        ...     def serialize(cls, value: Self) -> str:
        ...         return f"Serialized {self!r}"

    Note:
        Override and add serialization logic here, if necessary. The
        serialization to be invoked is set up in the schema. For more
        complex logic, you may want to override the
        `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`
        methods directly.
    """
    if info and info.mode == 'json':
        return __value.__str__()
    return __value

NameEmail

NameEmail(name: str, email: str)

Bases: BaseType, Representation

A formatted name and email address type.

It validates a name and email address combination as specified by RFC 5322. The type has two properties: name and email. If the name is not provided, it's inferred from the email address.

Examples:

>>> from plateforme import BaseModel
... from plateforme.types import NameEmail
>>> class User(BaseModel):
...     email: NameEmail
>>> user = User(email='Jane Bloggs <jane.bloggs@example.com>')
>>> print(user.email)
Jane Bloggs <jane.bloggs@example.com>
>>> print(user.email.name)
Jane Bloggs

Inialize a formatted name and email address.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/networks.py
def __init__(self, name: str, email: str):
    """Inialize a formatted name and email address."""
    self.name = name
    self.email = email

serialize classmethod

serialize(
    __value: Self, info: SerializationInfo | None = None
) -> Any

Return the serialized instance of the type.

Parameters:

Name Type Description Default
__value Self

Value to serialize.

required
info SerializationInfo | None

Additional information to pass to the serializer. Defaults to None.

None

Returns:

Type Description
Any

A serialized instance.

Examples:

>>> class MyType(BaseType, int):
...     @classmethod
...     def serialize(cls, value: Self) -> str:
...         return f"Serialized {self!r}"
Note

Override and add serialization logic here, if necessary. The serialization to be invoked is set up in the schema. For more complex logic, you may want to override the __get_pydantic_core_schema__ and __get_pydantic_json_schema__ methods directly.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/base.py
@classmethod
def serialize(
    cls, __value: Self, info: SerializationInfo | None = None
) -> Any:
    """Return the serialized instance of the type.

    Args:
        __value: Value to serialize.
        info: Additional information to pass to the serializer.
            Defaults to ``None``.

    Returns:
        A serialized instance.

    Examples:
        >>> class MyType(BaseType, int):
        ...     @classmethod
        ...     def serialize(cls, value: Self) -> str:
        ...         return f"Serialized {self!r}"

    Note:
        Override and add serialization logic here, if necessary. The
        serialization to be invoked is set up in the schema. For more
        complex logic, you may want to override the
        `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`
        methods directly.
    """
    if info and info.mode == 'json':
        return __value.__str__()
    return __value

EngineUrl dataclass

EngineUrl(
    conn: str,
    /,
    *,
    scheme: None = None,
    username: None = None,
    password: None = None,
    host: None = None,
    port: None = None,
    database: None = None,
)
EngineUrl(
    conn: None = None,
    /,
    *,
    scheme: str,
    username: str | None = None,
    password: str | None = None,
    host: str | None = None,
    port: int | None = None,
    database: str | None = None,
)
EngineUrl(
    conn: str | None = None,
    /,
    *,
    scheme: str | None = None,
    username: str | None = None,
    password: str | None = None,
    host: str | None = None,
    port: int | None = None,
    database: str | None = None,
)

A database engine URL type enforcing async driver selection.

Initialize a database engine URL.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/networks.py
def __init__(
    self,
    conn: str | None = None,
    /,
    *,
    scheme: str | None = None,
    username: str | None = None,
    password: str | None = None,
    host: str | None = None,
    port: int | None = None,
    database: str | None = None,
) -> None:
    """Initialize a database engine URL."""
    # Validate URL format
    if conn is not None:
        if scheme is not None:
            raise ValueError(
                f"Cannot specify both the URL connection and URL "
                f"components. Got: conn={conn}, scheme={scheme}."
            )
        # Handle SQLite in-memory and path URLs
        if conn == ':memory:':
            conn = 'sqlite+aiosqlite:///:memory:'
        elif conn.endswith('://'):
            conn += '/:memory:'
        elif ':' not in conn:
            conn = f'sqlite+aiosqlite:///{conn}'
        # Validate URL connection format
        match = re.match(RegexPattern.ENGINE, conn)
        if match is None:
            raise ValueError(
                f"Invalid database engine URL: {conn!r}. The provided "
                f"URL connection format must follow the pattern "
                f"`scheme://[username[:password]@]host[:port]/database`."
            )
        scheme, dialect, driver, \
            username, \
            password, \
            host, \
            port_str, \
            database = match.groups()
        if port_str is not None:
            port = int(port_str)
    else:
        if scheme is None:
            raise ValueError(
                "Missing database engine URL scheme. Please provide a "
                "valid URL scheme or URL connection."
            )
        # Validate URL scheme format
        match = re.match(RegexPattern.ENGINE_SCHEME, scheme)
        if not match:
            raise ValueError(
                f"Invalid database engine URL scheme: {scheme}. The "
                f"provided URL scheme format must follow the pattern "
                f"`dialect+driver`."
            )
        _, dialect, driver = match.groups()

    # Validate URL scheme dialect and driver
    if driver is None:
        if dialect not in DEFAULT_DRIVERS:
            raise ValueError(
                f"No default driver for database engine: {dialect}. "
                f"Please specify a valid driver in the URL scheme."
            )
        driver = DEFAULT_DRIVERS[dialect]
        scheme = f'{dialect}+{driver}'

    # Validate URL host and database
    if dialect == 'sqlite':
        if host is not None:
            raise ValueError(
                f"Invalid host for SQLite database engine: {host}. The "
                f"host must be omitted or set to `None`."
            )
        if database is None:
            raise ValueError(
                f"Missing database for SQLite database engine. The "
                f"database must be set to `:memory:` or a valid file path."
            )
    elif host is None:
        raise ValueError(
            f"Missing host for database engine: {dialect}. The host must "
            f"be set to a valid hostname or IP address."
        )

    object.__setattr__(self, 'scheme', scheme)
    object.__setattr__(self, 'username', username)
    object.__setattr__(self, 'password', password)
    object.__setattr__(self, 'host', host)
    object.__setattr__(self, 'port', port)
    object.__setattr__(self, 'database', database)

    # Validate final URL
    if conn is None and not re.match(RegexPattern.ENGINE, str(self)):
        raise ValueError(
            f"Invalid database engine URL: {self}. Please check the URL "
            f"components and try again."
        )

scheme instance-attribute

scheme: str

The scheme part of the URL.

username class-attribute instance-attribute

username: str | None = None

The username part of the URL, or omit for no username.

password class-attribute instance-attribute

password: str | None = None

The password part of the URL, or omit for no password.

host class-attribute instance-attribute

host: str | None = None

The host part of the URL.

port class-attribute instance-attribute

port: int | None = None

The port part of the URL, or omit for no port.

database class-attribute instance-attribute

database: str | None = None

The database part of the URL, or omit for no database path.

EngineMap

EngineMap(
    default: str | EngineUrl, **kwargs: str | EngineUrl
)

Bases: dict[str, EngineUrl]

A database engine URL map type.

Initialize a database engine URL map.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/networks.py
def __init__(
    self,
    default: str | EngineUrl,
    **kwargs: str | EngineUrl,
):
    """Initialize a database engine URL map."""
    engines = {'default': default, **kwargs}
    for key, value in engines.items():
        if isinstance(value, str):
            self[key] = EngineUrl(value)
        else:
            self[key] = value

IPvAddressFactory

Bases: BaseTypeFactory[IPvAddressFactoryAlias]

An IP address type factory.

It extends the built-in ipaddress.IPv4Address, ipaddress.IPv6Address, and pydantic IPvAnyAddress classes with additional validation and schema methods.

IPvInterfaceFactory

Bases: BaseTypeFactory[IPvInterfaceFactoryAlias]

An IP interface type factory.

It extends the built-in ipaddress.IPv4Interface, ipaddress.IPv6Interface, and pydantic IPvAnyInterface classes with additional validation and schema methods.

IPvNetworkFactory

Bases: BaseTypeFactory[IPvNetworkFactoryAlias]

An IP network type factory.

It extends the built-in ipaddress.IPv4Network, ipaddress.IPv6Network, and pydantic IPvAnyNetwork classes with additional validation and schema methods.

UrlFactory

Bases: BaseTypeFactory[PydanticUrl]

A URL type factory.

It extends the pydantic Url class with additional validation and schema methods.

MultiHostUrlFactory

Bases: BaseTypeFactory[PydanticMultiHostUrl]

A multi host URL type factory.

It extends the pydantic MultiHostUrl class with additional validation and schema methods.

plateforme.core.types.numbers

This module provides utilities for managing number types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

Boolean module-attribute

Boolean = Annotated[bool, ...]

The boolean proxy.

StrictBoolean module-attribute

StrictBoolean = Annotated[bool, ...]

A boolean that must be strict.

Decimal module-attribute

Decimal = Annotated[Decimal, ...]

The decimal proxy.

PositiveDecimal module-attribute

PositiveDecimal = Annotated[Decimal, ...]

A decimal that must be positive.

NegativeDecimal module-attribute

NegativeDecimal = Annotated[Decimal, ...]

A decimal that must be negative.

NonPositiveDecimal module-attribute

NonPositiveDecimal = Annotated[Decimal, ...]

A decimal that must be non-positive.

NonNegativeDecimal module-attribute

NonNegativeDecimal = Annotated[Decimal, ...]

A decimal that must be non-negative.

FiniteDecimal module-attribute

FiniteDecimal = Annotated[Decimal, ...]

A decimal that must be finite.

StrictDecimal module-attribute

StrictDecimal = Annotated[Decimal, ...]

A decimal that must be strict.

Float module-attribute

Float = Annotated[float, ...]

The float proxy.

PositiveFloat module-attribute

PositiveFloat = Annotated[float, ...]

A float that must be positive.

NegativeFloat module-attribute

NegativeFloat = Annotated[float, ...]

A float that must be negative.

NonPositiveFloat module-attribute

NonPositiveFloat = Annotated[float, ...]

A float that must be non-positive.

NonNegativeFloat module-attribute

NonNegativeFloat = Annotated[float, ...]

A float that must be non-negative.

FiniteFloat module-attribute

FiniteFloat = Annotated[float, ...]

A float that must be finite.

StrictFloat module-attribute

StrictFloat = Annotated[float, ...]

A float that must be strict.

Integer module-attribute

Integer = Annotated[int, ...]

The integer proxy.

PositiveInteger module-attribute

PositiveInteger = Annotated[int, ...]

An integer that must be positive.

NegativeInteger module-attribute

NegativeInteger = Annotated[int, ...]

An integer that must be negative.

NonPositiveInteger module-attribute

NonPositiveInteger = Annotated[int, ...]

An integer that must be non-positive.

NonNegativeInteger module-attribute

NonNegativeInteger = Annotated[int, ...]

An integer that must be non-negative.

StrictInteger module-attribute

StrictInteger = Annotated[int, ...]

An integer that must be strict.

AllowInfNan dataclass

AllowInfNan(allow_inf_nan: bool = True)

Bases: PydanticMetadata

A field metadata class to indicate that a field should allow -inf, inf, and nan.

BooleanFactory

Bases: BaseTypeFactory[bool]

A boolean type factory.

It extends the built-in bool class with additional validation and schema methods.

DecimalFactory

Bases: BaseTypeFactory[Decimal]

A decimal type factory.

It extends the built-in decimal.Decimal class with additional validation and schema methods.

FloatFactory

Bases: BaseTypeFactory[float]

A float type factory.

It extends the built-in float class with additional validation and schema methods.

IntegerFactory

Bases: BaseTypeFactory[int]

An integer type factory.

It extends the built-in int class with additional validation and schema methods.

plateforme.core.types.paths

This module provides utilities for managing path types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

AnyPath module-attribute

AnyPath = Annotated[Path, ...]

The path proxy.

DirectoryPath module-attribute

DirectoryPath = Annotated[Path, ...]

A path that must point to a directory.

FilePath module-attribute

FilePath = Annotated[Path, ...]

A path that must point to a file.

NewPath module-attribute

NewPath = Annotated[Path, ...]

A path for a new file or directory that must not already exist.

PathFactory

Bases: BaseTypeFactory[Path]

A path type factory.

It extends the built-in pathlib.Path class with additional validation and schema methods.

plateforme.core.types.secrets

This module provides utilities for managing secret types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

SecretType

SecretType(secret_value: _T)

Bases: BaseType, Generic[_T]

A secret type for storing sensitive information.

Initialize the secret type with the given value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
def __init__(self, secret_value: _T) -> None:
    """Initialize the secret type with the given value."""
    self._value: _T = secret_value

validate classmethod

validate(
    __value: Any, info: ValidationInfo | None = None
) -> Self

Validate value and return a new instance of the type.

Parameters:

Name Type Description Default
__value Any

Value to validate.

required
info ValidationInfo | None

Addition information to pass to the validator. Defaults to None.

None

Returns:

Type Description
Self

A type initialized with validated value.

Examples:

>>> class MyType(BaseType, int):
...     @classmethod
...     def validate(cls, value: Any) -> Self:
...         if value < 0:
...             raise ValueError('Value must be positive.')
...         return cls(value)
>>> MyType(1)
1
>>> MyType(-1)
ValueError: Value must be positive.
Note

Override and add validation logic here, if necessary. The validation is performed after the schema validation. For more complex logic, you may want to override the __get_pydantic_core_schema__ and __get_pydantic_json_schema__ methods directly.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/base.py
@classmethod
def validate(
    cls, __value: Any, info: ValidationInfo | None = None
) -> Self:
    """Validate value and return a new instance of the type.

    Args:
        __value: Value to validate.
        info: Addition information to pass to the validator.
            Defaults to ``None``.

    Returns:
        A type initialized with validated `value`.

    Examples:
        >>> class MyType(BaseType, int):
        ...     @classmethod
        ...     def validate(cls, value: Any) -> Self:
        ...         if value < 0:
        ...             raise ValueError('Value must be positive.')
        ...         return cls(value)
        >>> MyType(1)
        1
        >>> MyType(-1)
        ValueError: Value must be positive.

    Note:
        Override and add validation logic here, if necessary. The
        validation is performed after the schema validation. For more
        complex logic, you may want to override the
        `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`
        methods directly.
    """
    return cls(__value)

get_secret_value

get_secret_value() -> _T

Get the secret value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
def get_secret_value(self) -> _T:
    """Get the secret value."""
    return self._value

serialize classmethod

serialize(
    value: Self, info: SerializationInfo | None = None
) -> Self | str

Serialize the secret value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
@classmethod
def serialize(
    cls, value: Self, info: SerializationInfo | None = None
) -> Self | str:
    """Serialize the secret value."""
    if info and info.mode == 'json':
        return _secret_display(value.get_secret_value())
    return value

SecretStr

SecretStr(secret_value: _T)

Bases: SecretType[str]

A secret string type.

It is used for storing sensitive information that you do not want to be visible in logging or tracebacks. When the secret value is nonempty, it is displayed as '**********' instead of the underlying value in calls to repr() and str(). If the value is empty, it is displayed as ''.

Examples:

>>> from plateforme import BaseModel
... from plateforme.types import SecretStr
>>> class User(BaseModel):
...     username: str
...     password: SecretStr
... user = User(username='johndoe', password='kLj4$2')
>>> print(user)
username='johndoe' password=SecretStr('**********')
>>> print(user.password.get_secret_value())
kLj4$2
>>> print((SecretStr('password'), SecretStr('')))
(SecretStr('**********'), SecretStr(''))

Initialize the secret type with the given value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
def __init__(self, secret_value: _T) -> None:
    """Initialize the secret type with the given value."""
    self._value: _T = secret_value

validate classmethod

validate(
    __value: Any, info: ValidationInfo | None = None
) -> Self

Validate value and return a new instance of the type.

Parameters:

Name Type Description Default
__value Any

Value to validate.

required
info ValidationInfo | None

Addition information to pass to the validator. Defaults to None.

None

Returns:

Type Description
Self

A type initialized with validated value.

Examples:

>>> class MyType(BaseType, int):
...     @classmethod
...     def validate(cls, value: Any) -> Self:
...         if value < 0:
...             raise ValueError('Value must be positive.')
...         return cls(value)
>>> MyType(1)
1
>>> MyType(-1)
ValueError: Value must be positive.
Note

Override and add validation logic here, if necessary. The validation is performed after the schema validation. For more complex logic, you may want to override the __get_pydantic_core_schema__ and __get_pydantic_json_schema__ methods directly.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/base.py
@classmethod
def validate(
    cls, __value: Any, info: ValidationInfo | None = None
) -> Self:
    """Validate value and return a new instance of the type.

    Args:
        __value: Value to validate.
        info: Addition information to pass to the validator.
            Defaults to ``None``.

    Returns:
        A type initialized with validated `value`.

    Examples:
        >>> class MyType(BaseType, int):
        ...     @classmethod
        ...     def validate(cls, value: Any) -> Self:
        ...         if value < 0:
        ...             raise ValueError('Value must be positive.')
        ...         return cls(value)
        >>> MyType(1)
        1
        >>> MyType(-1)
        ValueError: Value must be positive.

    Note:
        Override and add validation logic here, if necessary. The
        validation is performed after the schema validation. For more
        complex logic, you may want to override the
        `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`
        methods directly.
    """
    return cls(__value)

serialize classmethod

serialize(
    value: Self, info: SerializationInfo | None = None
) -> Self | str

Serialize the secret value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
@classmethod
def serialize(
    cls, value: Self, info: SerializationInfo | None = None
) -> Self | str:
    """Serialize the secret value."""
    if info and info.mode == 'json':
        return _secret_display(value.get_secret_value())
    return value

get_secret_value

get_secret_value() -> _T

Get the secret value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
def get_secret_value(self) -> _T:
    """Get the secret value."""
    return self._value

SecretBytes

SecretBytes(secret_value: _T)

Bases: SecretType[bytes]

A secret bytes type.

It is used for storing sensitive information that you do not want to be visible in logging or tracebacks. When the secret value is nonempty, it is displayed as b'**********' instead of the underlying value in calls to repr() and str(). If the value is empty, it is displayed as b''.

Examples:

>>> from plateforme import BaseModel
... from plateforme.types import SecretBytes
>>> class User(BaseModel):
...     username: str
...     password: SecretBytes
... user = User(username='johndoe', password=b'kLj4$2')
>>> print(user)
username='johndoe' password=SecretBytes(b'**********')
>>> print(user.password.get_secret_value())
b'kLj4$2'
>>> print((SecretBytes(b'password'), SecretBytes(b'')))
(SecretBytes(b'**********'), SecretBytes(b''))

Initialize the secret type with the given value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
def __init__(self, secret_value: _T) -> None:
    """Initialize the secret type with the given value."""
    self._value: _T = secret_value

validate classmethod

validate(
    __value: Any, info: ValidationInfo | None = None
) -> Self

Validate value and return a new instance of the type.

Parameters:

Name Type Description Default
__value Any

Value to validate.

required
info ValidationInfo | None

Addition information to pass to the validator. Defaults to None.

None

Returns:

Type Description
Self

A type initialized with validated value.

Examples:

>>> class MyType(BaseType, int):
...     @classmethod
...     def validate(cls, value: Any) -> Self:
...         if value < 0:
...             raise ValueError('Value must be positive.')
...         return cls(value)
>>> MyType(1)
1
>>> MyType(-1)
ValueError: Value must be positive.
Note

Override and add validation logic here, if necessary. The validation is performed after the schema validation. For more complex logic, you may want to override the __get_pydantic_core_schema__ and __get_pydantic_json_schema__ methods directly.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/base.py
@classmethod
def validate(
    cls, __value: Any, info: ValidationInfo | None = None
) -> Self:
    """Validate value and return a new instance of the type.

    Args:
        __value: Value to validate.
        info: Addition information to pass to the validator.
            Defaults to ``None``.

    Returns:
        A type initialized with validated `value`.

    Examples:
        >>> class MyType(BaseType, int):
        ...     @classmethod
        ...     def validate(cls, value: Any) -> Self:
        ...         if value < 0:
        ...             raise ValueError('Value must be positive.')
        ...         return cls(value)
        >>> MyType(1)
        1
        >>> MyType(-1)
        ValueError: Value must be positive.

    Note:
        Override and add validation logic here, if necessary. The
        validation is performed after the schema validation. For more
        complex logic, you may want to override the
        `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`
        methods directly.
    """
    return cls(__value)

serialize classmethod

serialize(
    value: Self, info: SerializationInfo | None = None
) -> Self | str

Serialize the secret value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
@classmethod
def serialize(
    cls, value: Self, info: SerializationInfo | None = None
) -> Self | str:
    """Serialize the secret value."""
    if info and info.mode == 'json':
        return _secret_display(value.get_secret_value())
    return value

get_secret_value

get_secret_value() -> _T

Get the secret value.

Source code in .venv/lib/python3.12/site-packages/plateforme/core/types/secrets.py
def get_secret_value(self) -> _T:
    """Get the secret value."""
    return self._value

plateforme.core.types.strings

This module provides utilities for managing string types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

String module-attribute

String = Annotated[str, ...]

The string proxy.

StrictString module-attribute

StrictString = Annotated[str, ...]

A string that must be validated strictly.

StringFactory

Bases: BaseTypeFactory[str]

A string type factory.

It extends the built-in str class with additional validation and schema methods.

plateforme.core.types.uuid

This module provides utilities for managing UUID types within the Plateforme framework leveraging Pydantic schemas for validation and serialization, and compatibility with SQLAlchemy's data type system.

UUID module-attribute

UUID = Annotated[UUID, ...]

The UUID proxy.

UUID1 module-attribute

UUID1 = Annotated[UUID, ...]

A UUID that must be of version 1.

UUID3 module-attribute

UUID3 = Annotated[UUID, ...]

A UUID that must be of version 3.

UUID4 module-attribute

UUID4 = Annotated[UUID, ...]

A UUID that must be of version 4.

UUID5 module-attribute

UUID5 = Annotated[UUID, ...]

A UUID that must be of version 5.

UuidVersion dataclass

UuidVersion(uuid_version: Literal[1, 3, 4, 5])

A field metadata class to indicate a UUID version.

UuidFactory

Bases: BaseTypeFactory[UUID]

An UUID type factory.

It extends the built-in uuid.UUID class with additional validation and schema methods.