Enhance ModelView class with iterable and indexing support

- Added iterator, length, and item access methods to the `ModelView` class, allowing it to handle single models and lists more effectively.
- Refactored the `vlans` method in the `Keenetic` model to restore functionality for decoding VLAN descriptions, improving data processing consistency.
This commit is contained in:
IluaAir
2026-02-24 23:19:57 +03:00
parent 3159570e27
commit ac835d6b56
2 changed files with 23 additions and 8 deletions

View File

@@ -1,6 +1,6 @@
from functools import cached_property from functools import cached_property
import json import json
from typing import TYPE_CHECKING, Generic, TypeVar from typing import TYPE_CHECKING, Generic, Iterator, Type, TypeVar
from pydantic import BaseModel from pydantic import BaseModel
@@ -24,6 +24,21 @@ class ModelView(Generic[TModel]):
) )
return self._model.model_dump_json(by_alias=True) return self._model.model_dump_json(by_alias=True)
def __iter__(self) -> Iterator[TModel]:
if isinstance(self._model, list):
return iter(self._model)
raise TypeError("This view wraps a single model, not a list")
def __len__(self) -> int:
if isinstance(self._model, list):
return len(self._model)
raise TypeError("This view wraps a single model, not a list")
def __getitem__(self, item):
if isinstance(self._model, list):
return self._model[item]
raise TypeError("This view wraps a single model, not a list")
def __getattr__(self, item): def __getattr__(self, item):
return getattr(self._model, item) return getattr(self._model, item)

View File

@@ -33,13 +33,13 @@ class Keenetic(BaseDevice):
item["description"] = decoded item["description"] = decoded
return interfaces return interfaces
# def vlans(self): def vlans(self):
# vlans = self.raw["vlans"] vlans = self.raw["vlans"]
# for item in vlans: for item in vlans:
# if item.get("description"): if item.get("description"):
# decoded = self._decode_utf(item.get("description", "")) decoded = self._decode_utf(item.get("description", ""))
# item["description"] = decoded item["description"] = decoded
# return vlans return vlans
if __name__ == "__main__": if __name__ == "__main__":