|
| 1 | +""" |
| 2 | +Base model shared by every Shade API response object. |
| 3 | +""" |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from typing import Any, ClassVar, Optional |
| 7 | + |
| 8 | +from pydantic import BaseModel, ConfigDict, ValidationError |
| 9 | + |
| 10 | +from ..errors import InvalidRequestError |
| 11 | + |
| 12 | + |
| 13 | +class ShadeObject(BaseModel): |
| 14 | + """Base class for API response models. |
| 15 | +
|
| 16 | + Subclasses get dict round-tripping (:meth:`from_dict` / :meth:`to_dict`) and a |
| 17 | + readable ``repr``. Unknown fields returned by the API are preserved rather than |
| 18 | + rejected, so a server-side addition never breaks an older SDK. |
| 19 | +
|
| 20 | + Attributes: |
| 21 | + _id_field: Name of the field shown in ``repr``. Subclasses that do not use |
| 22 | + a plain ``id`` should override it (e.g. ``_id_field = "invoice_id"``). |
| 23 | + """ |
| 24 | + |
| 25 | + model_config = ConfigDict(populate_by_name=True, extra="allow") |
| 26 | + |
| 27 | + _id_field: ClassVar[str] = "id" |
| 28 | + |
| 29 | + def __init__(self, **data: Any) -> None: |
| 30 | + try: |
| 31 | + super().__init__(**data) |
| 32 | + except ValidationError as exc: |
| 33 | + raise _as_invalid_request(type(self), exc) from exc |
| 34 | + |
| 35 | + @classmethod |
| 36 | + def from_dict(cls, data: dict) -> "ShadeObject": |
| 37 | + """Build a model from a decoded JSON object. |
| 38 | +
|
| 39 | + Raises: |
| 40 | + InvalidRequestError: If ``data`` is not a dict or fails validation. |
| 41 | + """ |
| 42 | + if not isinstance(data, dict): |
| 43 | + raise InvalidRequestError( |
| 44 | + f"{cls.__name__}.from_dict() expects a dict, got " |
| 45 | + f"{type(data).__name__}" |
| 46 | + ) |
| 47 | + return cls(**data) |
| 48 | + |
| 49 | + def to_dict(self, **kwargs: Any) -> dict: |
| 50 | + """Return the model as a plain dict, keyed by field alias where one exists. |
| 51 | +
|
| 52 | + Any keyword arguments are forwarded to ``model_dump``. |
| 53 | + """ |
| 54 | + kwargs.setdefault("by_alias", True) |
| 55 | + return self.model_dump(**kwargs) |
| 56 | + |
| 57 | + def __repr__(self) -> str: |
| 58 | + identifier = self._identifier() |
| 59 | + if identifier is None: |
| 60 | + return f"<{type(self).__name__}>" |
| 61 | + return f"<{type(self).__name__} {self._id_field}={identifier!r}>" |
| 62 | + |
| 63 | + def _identifier(self) -> Optional[Any]: |
| 64 | + """Value of the model's primary ID field, or ``None`` when it has none.""" |
| 65 | + return getattr(self, self._id_field, None) |
| 66 | + |
| 67 | + |
| 68 | +def _as_invalid_request( |
| 69 | + model: type[BaseModel], |
| 70 | + exc: ValidationError, |
| 71 | +) -> InvalidRequestError: |
| 72 | + """Translate a pydantic ValidationError into the SDK's InvalidRequestError.""" |
| 73 | + errors = exc.errors() |
| 74 | + field_errors: dict[str, list[str]] = {} |
| 75 | + for error in errors: |
| 76 | + location = ".".join(str(part) for part in error["loc"]) or "__root__" |
| 77 | + field_errors.setdefault(location, []).append(error["msg"]) |
| 78 | + |
| 79 | + count = len(errors) |
| 80 | + plural = "" if count == 1 else "s" |
| 81 | + first = next(iter(field_errors), None) |
| 82 | + return InvalidRequestError( |
| 83 | + f"{count} validation error{plural} for {model.__name__}", |
| 84 | + param=first, |
| 85 | + field_errors=field_errors, |
| 86 | + ) |
0 commit comments