From fe48f9a17ef856a60e0fcb674fb2fd174fb1ab9b Mon Sep 17 00:00:00 2001 From: Ivan Habunek Date: Thu, 16 Nov 2023 15:12:51 +0100 Subject: [PATCH] Add a way to preprocess the data before decoding Use it to modify the data returned by the Pleroma API which does not conform to the current Mastodon API definition. See: https://git.pleroma.social/pleroma/pleroma/-/issues/1470#anchor-310 --- toot/entities.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/toot/entities.py b/toot/entities.py index 6ba5553..1dc61cd 100644 --- a/toot/entities.py +++ b/toot/entities.py @@ -1,5 +1,11 @@ """ Dataclasses which represent entities returned by the Mastodon API. + +Data classes my have an optional static method named `__toot_prepare__` which is +used when constructing the data class using `from_dict`. The method will be +called with the dict and may modify it and return a modified dict. This is used +to implement any pre-processing which may be required, e.g. to support +different versions of the Mastodon API. """ import dataclasses @@ -66,6 +72,16 @@ class Account: followers_count: int following_count: int + @staticmethod + def __toot_prepare__(obj: Dict) -> Dict: + # Pleroma has not yet converted last_status_at from datetime to date + # so trim it here so it doesn't break when converting to date. + # See: https://git.pleroma.social/pleroma/pleroma/-/issues/1470 + last_status_at = obj.get("last_status_at") + if last_status_at: + obj.update(last_status_at=obj["last_status_at"][:10]) + return obj + @property def note_plaintext(self) -> str: return get_text(self.note) @@ -362,6 +378,11 @@ T = TypeVar("T") def from_dict(cls: Type[T], data: Dict) -> T: """Convert a nested dict into an instance of `cls`.""" + # Apply __toot_prepare__ if it exists + prepare = getattr(cls, '__toot_prepare__', None) + if prepare: + data = prepare(data) + def _fields(): hints = get_type_hints(cls) for field in dataclasses.fields(cls):