Skip to content

Commit

Permalink
include some status defaults when serializing
Browse files Browse the repository at this point in the history
  • Loading branch information
FynnBe committed Nov 13, 2024
1 parent a16de50 commit e58a425
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
27 changes: 26 additions & 1 deletion bioimageio_collection_backoffice/common.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
from typing import Any, ClassVar, Dict, FrozenSet, Union

import pydantic
from pydantic_core import PydanticUndefined
from typing_extensions import LiteralString


class Node(
Expand All @@ -12,4 +16,25 @@ class Node(
):
"""""" # avoid inheriting docstring from `pydantic.BaseModel`

pass
fields_to_set_explicitly: ClassVar[FrozenSet[LiteralString]] = frozenset()
"""set set these fields explicitly with their default value if they are not set,
such that they are always included even when dumping with 'exlude_unset'"""

@pydantic.model_validator(mode="before")
@classmethod
def set_fields_explicitly(
cls, data: Union[Any, Dict[str, Any]]
) -> Union[Any, Dict[str, Any]]:
if isinstance(data, dict):
for name in cls.fields_to_set_explicitly:
if (
name not in data
and name in cls.model_fields
and (
(field_info := cls.model_fields[name]) is not PydanticUndefined
or field_info.default_factory is not None
)
):
data[name] = field_info.get_default(call_default_factory=True)

return data # pyright: ignore[reportUnknownVariableType]
15 changes: 13 additions & 2 deletions bioimageio_collection_backoffice/db_structure/version_info.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
from __future__ import annotations

from datetime import datetime
from typing import ClassVar, List, Literal, Optional, Sequence, Union
from typing import (
ClassVar,
FrozenSet,
List,
Literal,
Optional,
Sequence,
Union,
)

import pydantic
from typing_extensions import Annotated
from typing_extensions import Annotated, LiteralString

from .._settings import settings
from ..common import Node


class _StatusBase(Node, frozen=True):
fields_to_set_explicitly: ClassVar[FrozenSet[LiteralString]] = frozenset(
{"name", "step", "num_steps", "description"}
)
timestamp: datetime = pydantic.Field(default_factory=datetime.now)
run_url: Optional[str] = settings.run_url

Expand Down

0 comments on commit e58a425

Please sign in to comment.