Reference
Schemas¶
hinoki.schema.Schema ¶
Base class for schemas.
class PostCreate(Schema): title: str becomes a frozen, keyword-only
dataclass. PostCreate.validate(data) checks decoded JSON strictly:
no coercion, unknown keys refused by default, and every problem reported
with its path.
computed_fields
classmethod
¶
computed_fields() -> dict[str, ComputedSpec]
The read-only values this schema adds to its output, by name.
apply_default
classmethod
¶
apply_default(name: str) -> None
Turn a Field(default_factory=...) attribute into a dataclass default.
specs
classmethod
¶
specs() -> dict[str, FieldSpec]
Field descriptions, resolving forward references on first use.
validate_normalizers
classmethod
¶
validate_normalizers(specs: dict[str, FieldSpec]) -> None
Check that registered normalizers have a precise typed target.
native_schema
classmethod
¶
native_schema() -> core.CompiledSchema
The Rust validator for this schema and everything it refers to, compiled on first use and cached on the class.
validate
classmethod
¶
validate(data: object) -> Self
Build an instance from decoded JSON or raise ValidationError
(validated in Rust).
validate_text
classmethod
¶
validate_text(data: object) -> Self
Like validate for data that is all text, such as form fields
({"count": ["2"]}) or a parsed XML tree: text is first converted, in
Rust, to the int, float and bool the fields declare. Anything
that does not convert is left for validate to refuse. Before hooks see
the raw text (each form value is a list of strings) and run first.
fields
classmethod
¶
fields() -> dict[str, FieldSpec]
Immutable description shared by binding, docs and rules.
to_dict ¶
to_dict(*, exclude: Iterable[str] = ()) -> dict[str, Any]
The field values as Python objects (UUID, datetime stay what they are),
nested schemas converted too. Fields left UNSET are omitted, so the
result is exactly "what the client sent" for a partial update.
replace ¶
replace(**changes: Any) -> Self
A copy with changes (Python field names) applied. Every value is
validated again, normalised and checked like a new instance, so the copy
is as trustworthy as any other; fields that were never supplied stay
unsupplied for dump(exclude_unset=True).
from_models
classmethod
¶
from_models(
rows: Iterable[object], **extra: Any
) -> list[Self]
Build a list from a synchronous iterable of model rows.
Each row follows from_model exactly. The iterable is consumed once,
eagerly; this reads already-loaded attributes and never performs I/O.
from_model
classmethod
¶
from_model(row: object, **extra: Any) -> Self
Build this schema from a model instance: every field is read from the
attribute of the same name, extra supplies or overrides values (for
computed fields). Nested models become nested schemas. A field the row
lacks is an error, and an unloaded relation still raises
RelationNotLoaded: nothing here does I/O.
dump ¶
dump(
*,
include: Iterable[str] | None = None,
exclude: Iterable[str] = (),
exclude_unset: bool = False,
by_alias: bool = True,
) -> dict[str, Any]
Return JSON-compatible data with optional projection controls.
Selectors use Python field names. exclude_unset omits defaulted
fields not supplied at construction. HTTP responses use default options.
hinoki.schemaconfig.SchemaConfig
dataclass
¶
SchemaConfig(*, extra: SchemaExtra = SchemaExtra.FORBID)
Immutable class-level Schema behavior configuration.
hinoki.schemaconfig.SchemaExtra ¶
Bases: StrEnum
Policy for unknown string keys in decoded Schema input.
hinoki.fields.Field ¶
Field(
*,
default_factory: Callable[[], T],
alias: str | None = None,
) -> T
Field(
*,
alias: str,
min_length: int | None = None,
max_length: int | None = None,
pattern: str | None = None,
ge: float | Decimal | None = None,
le: float | Decimal | None = None,
gt: float | Decimal | None = None,
lt: float | Decimal | None = None,
one_of: Sequence[Any] | None = None,
max_digits: int | None = None,
decimal_places: int | None = None,
multiple_of: int | Decimal | None = None,
strip: bool | None = None,
lower: bool | None = None,
upper: bool | None = None,
format: str | None = None,
discriminator: str | None = None,
description: str | None = None,
examples: Sequence[Any] | None = None,
deprecated: bool | None = None,
) -> Any
Field(
*,
min_length: int | None = None,
max_length: int | None = None,
pattern: str | None = None,
ge: float | Decimal | None = None,
le: float | Decimal | None = None,
gt: float | Decimal | None = None,
lt: float | Decimal | None = None,
one_of: Sequence[Any] | None = None,
max_digits: int | None = None,
decimal_places: int | None = None,
multiple_of: int | Decimal | None = None,
strip: bool | None = None,
lower: bool | None = None,
upper: bool | None = None,
format: str | None = None,
alias: str | None = None,
discriminator: str | None = None,
description: str | None = None,
examples: Sequence[Any] | None = None,
deprecated: bool | None = None,
) -> FieldInfo
Field(**options: Any) -> Any
Declare constraints (inside Annotated) or a default factory.
tags: list[str] = Field(default_factory=list) gives a per-instance
default; title: Annotated[str, Field(min_length=1)] adds constraints.
hinoki.schema.Invalid ¶
Invalid(code: str, message: str, *, path: str = '')
Bases: Exception
Raised by a check to refuse a value: a stable code, a readable
message and optionally the path it concerns (default: the field the
check is attached to, or the object itself).
hinoki.schema.Unset ¶
Type of UNSET: a field that was absent from the input (PATCH).
hinoki.schema.field_check ¶
field_check(*names: str) -> Callable[[F], F]
Mark a method as a check on one or more fields: def ok(self, value).
It runs after the structural validation succeeded, so value already has
the declared type, and may read the other fields through self. Raise
Invalid(code, message) to refuse; it never changes the value. Checks are
synchronous and must not do I/O: a rule that needs the database belongs in an
operation, not in a schema.
hinoki.schema.field_normalize ¶
field_normalize(name: str) -> Callable[[F], F]
Mark a typed field canonicalizer: def trim(self, value: str) -> str.
Methods run synchronously after structural validation and return a
replacement string; raise Invalid only from a check hook to reject.
hinoki.schema.object_check ¶
object_check(function: F) -> F
Mark a method as a check on the whole object: def ok(self). Runs after
every field check passed or failed (all problems are reported together).
hinoki.schema.before_validate ¶
before_validate(function: F) -> F
Mark a classmethod or staticmethod that reshapes raw wire input:
def prepare(cls, data: dict[str, Any]) -> dict[str, Any].
It runs on the decoded mapping, before any structural validation, for the
schema and for every schema nested in it (lists, dicts, tuples, optionals and
discriminated variants). Return the mapping to validate. The hook gets a shallow
copy: replace nested values instead of mutating them, or the caller's input
changes. Raise Invalid(code, message) to refuse; a KeyError,
TypeError, ValueError, IndexError or AttributeError caused by
unexpected input answers as invalid_input. The input
is untrusted: check types before relying on them, stay synchronous and do no
I/O. Plain unions of schemas that use it are refused: use a discriminator.
hinoki.computed.computed_field ¶
computed_field(function: Callable[[Any], T]) -> T
computed_field(
*,
alias: str | None = None,
description: str | None = None,
examples: Sequence[Any] | None = None,
) -> Callable[[Callable[[Any], T]], T]
computed_field(
function: Callable[..., Any] | None = None,
/,
*,
alias: str | None = None,
description: str | None = None,
examples: Sequence[Any] | None = None,
) -> Any
Declare a read-only value derived from the other fields of a Schema.
@computed_field def full_name(self) -> str reads like an attribute, is
written by dump() and by JSON responses after the declared fields, and
is documented as a readOnly property. It is never accepted as input and
never stored. The return annotation gives its OpenAPI type; the method must
be synchronous, take no arguments and not do I/O.
hinoki.fields.SecretStr ¶
SecretStr(value: str)
A string that never shows itself: repr, str, dump() and JSON
responses give **********; get_secret_value() returns the text.
hinoki.errors.ValidationError ¶
ValidationError(details: list[ErrorDetail])
Bases: Exception
Input does not match a schema. details lists every problem found.
hinoki.derive.derive ¶
derive(
model: type[Model] | None = None,
*,
only: tuple[str, ...] | None = None,
exclude: tuple[str, ...] | None = None,
partial: bool | tuple[str, ...] = False,
) -> Callable[[type[S]], type[S]]
Derive selected fields from model into a Schema subclass.
The keyword-only form is retained for one compatibility cycle and is
deprecated; it requires the legacy model= Schema class keyword.