Skip to content

Commit

Permalink
🐛 SerializationMeta 适配 Pydantic V2
Browse files Browse the repository at this point in the history
  • Loading branch information
he0119 committed Feb 13, 2024
1 parent 673227b commit 30b0173
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 14 deletions.
39 changes: 27 additions & 12 deletions nonebot_plugin_saa/registries/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,40 @@ class SerializationMeta(BaseModel, ABC):
frozen=True,
orm_mode=True,
)

@classmethod
def __pydantic_init_subclass__(cls, *args, **kwargs) -> None:
if cls._level == Level.MetaBase:
cls._level = Level.Base
cls._deserializer_dict = {}
elif cls._level == Level.Base:
cls._level = Level.Normal
cls._deserializer_dict[cls.model_fields[cls._index_key].default] = cls
elif cls._level == Level.Normal:
pass
else:
raise RuntimeError("SerializationMeta init error")

else:

class Config:
frozen = True
orm_mode = True

def __init_subclass__(cls, *args, **kwargs) -> None:
if cls._level == Level.MetaBase:
cls._level = Level.Base
cls._deserializer_dict = {}
elif cls._level == Level.Base:
cls._level = Level.Normal
cls._deserializer_dict[cls.__fields__[cls._index_key].default] = cls
elif cls._level == Level.Normal:
pass
else:
raise RuntimeError("SerializationMeta init error")
@classmethod
def __init_subclass__(cls, *args, **kwargs) -> None:
if cls._level == Level.MetaBase:
cls._level = Level.Base
cls._deserializer_dict = {}
elif cls._level == Level.Base:
cls._level = Level.Normal
cls._deserializer_dict[cls.__fields__[cls._index_key].default] = cls
elif cls._level == Level.Normal:
pass
else:
raise RuntimeError("SerializationMeta init error")

super().__init_subclass__(*args, **kwargs)
super().__init_subclass__(*args, **kwargs)

@classmethod
def deserialize(cls, source: Any) -> Self:
Expand Down
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions tests/test_platform_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ class MySendTarget(PlatformTarget):
platform_type: Literal[SupportedPlatform.qq_group] = SupportedPlatform.qq_group
my_field: int

def test(self):
return self.my_field

send_target = MySendTarget(my_field=123)
send_target.test()
serialized_target = send_target.json()
deserialized_target = PlatformTarget.deserialize(serialized_target)

Expand Down
2 changes: 1 addition & 1 deletion tests/test_send.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,6 @@ async def test_matcher():
"detail_type": "private",
"user_id": event.user_id,
},
result={"message_id": 12451},
result={"message_id": "12451"},
)
assertion(ctx)

0 comments on commit 30b0173

Please sign in to comment.