jean-web/jweb/content.py

48 lines
1.3 KiB
Python

from pathlib import Path
from typing import Any, Generic, Iterator, TypeVar
TData = TypeVar("TData")
class Content(Generic[TData]):
def __init__(self, path: Path, data: TData, language: str | None = None) -> None:
self.__path = path
self.__data = data
self.__language = language
@property
def path(self) -> Path:
return self.__path
@property
def language(self) -> str | None:
return self.__language
@property
def data(self) -> TData:
return self.__data
def __str__(self) -> str:
return str(self.__data)
class ContentField:
def __init__(self, owner_content_path: Path, value: Any) -> None:
self.__owner_content_path = owner_content_path
self.__value = value
def __getitem__(self, key: Any) -> Any:
return ContentField(self.__owner_content_path, self.__value.get(key))
def __iter__(self) -> Iterator[Any]:
for it in self.__value:
yield ContentField(self.__owner_content_path, it)
def __str__(self) -> str:
return str(self.__value)
def as_path(self) -> Path:
if not isinstance(self.__value, (str, Path)):
raise ValueError("You can't use a field of type %s as a path", type(self.__value))
return self.__owner_content_path.parent / str(self)