Skip to content

Commit

Permalink
✨ 适配 Pydantic V2
Browse files Browse the repository at this point in the history
  • Loading branch information
he0119 committed Feb 19, 2024
1 parent c9feb7e commit 7d8f4ca
Show file tree
Hide file tree
Showing 16 changed files with 279 additions and 156 deletions.
3 changes: 2 additions & 1 deletion nonebot_plugin_saa/adapters/dodo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from nonebot import logger
from nonebot.adapters import Event
from nonebot.drivers import Request
from nonebot.compat import model_dump
from nonebot.adapters import Bot as BaseBot

from ..types import Text, Image, Reply, Mention
Expand Down Expand Up @@ -86,7 +87,7 @@ async def _image(image: Image, bot: BaseBot) -> MessageSegment:
file=file, file_name=image.data["name"] + ".png" # 上传是文件名必须携带有效后缀
)
logger.debug(f"Uploaded result: {upload_result}")
return MessageSegment.picture(**upload_result.dict())
return MessageSegment.picture(**model_dump(upload_result))

@register_dodo(Reply)
def _reply(reply: Reply) -> MessageSegment:
Expand Down
5 changes: 3 additions & 2 deletions nonebot_plugin_saa/adapters/onebot_v12.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import List, Literal

from nonebot.adapters import Event
from nonebot.compat import model_dump
from nonebot.adapters import Bot as BaseBot

from ..types import Text, Image, Reply, Mention
Expand Down Expand Up @@ -105,7 +106,7 @@ def _extract_private_msg_event(event: Event) -> PlatformTarget:
if event.self.platform == "qq":
return TargetQQPrivate(user_id=int(event.user_id))
if event.self.platform == "qqguild":
event_dict = event.dict()
event_dict = model_dump(event)
return TargetQQGuildDirect(
recipient_id=int(event.user_id),
source_guild_id=event_dict["qqguild"]["src_guild_id"],
Expand Down Expand Up @@ -240,7 +241,7 @@ async def _qqguild_dms(target: TargetQQGuildDirect, bot: BaseBot) -> int:
@register_convert_to_arg(adapter, SupportedPlatform.unknown_ob12)
def _to_unknow(target: PlatformTarget):
assert isinstance(target, TargetOB12Unknow)
return target.dict(exclude={"platform", "platform_type"})
return model_dump(target, exclude={"platform", "platform_type"})

class OB12Receipt(Receipt):
message_id: str
Expand Down
3 changes: 2 additions & 1 deletion nonebot_plugin_saa/auto_select_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import nonebot
from nonebot.adapters import Bot
from nonebot import logger, get_bots
from nonebot.compat import model_dump

from .registries import BotSpecifier, PlatformTarget, TargetQQGuildDirect
from .utils import (
Expand Down Expand Up @@ -133,5 +134,5 @@ def get_bot(target: PlatformTarget) -> Bot:
def _info_current():
log_info = {}
for bot, platform_target_set in BOT_CACHE.items():
log_info[str(bot)] = [target.dict() for target in platform_target_set]
log_info[str(bot)] = [model_dump(target) for target in platform_target_set]
logger.trace(f"current bot-platform_target: {json.dumps(log_info)}")
4 changes: 2 additions & 2 deletions nonebot_plugin_saa/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from nonebot import get_driver
from nonebot import get_plugin_config
from pydantic import Field, BaseModel


Expand All @@ -17,4 +17,4 @@ class Config(BaseModel):
"""峯驰物流插件配置"""


plugin_config = Config.parse_obj(get_driver().config).saa
plugin_config = get_plugin_config(Config).saa
34 changes: 26 additions & 8 deletions nonebot_plugin_saa/registries/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import Any, Dict, ClassVar

from pydantic import BaseModel
from nonebot.compat import PYDANTIC_V2, ConfigDict, type_validate_python


class Level(Enum):
Expand All @@ -18,24 +19,41 @@ class SerializationMeta(BaseModel, ABC):
_deserializer_dict: ClassVar[Dict]
_level: ClassVar[Level] = Level.MetaBase

class Config:
frozen = True
orm_mode = True
if PYDANTIC_V2:
model_config = ConfigDict(
frozen=True,
from_attributes=True,
)

def __init_subclass__(cls, *args, **kwargs) -> None:
@classmethod
def __pydantic_init_subclass__(cls, *args, **kwargs) -> None:
cls._register_subclass(cls.model_fields)

else:

class Config:
frozen = True
orm_mode = True

Check warning on line 36 in nonebot_plugin_saa/registries/meta.py

View check run for this annotation

Codecov / codecov/patch

nonebot_plugin_saa/registries/meta.py#L34-L36

Added lines #L34 - L36 were not covered by tests

@classmethod
def __init_subclass__(cls, *args, **kwargs) -> None:
cls._register_subclass(cls.__fields__)

Check warning on line 40 in nonebot_plugin_saa/registries/meta.py

View check run for this annotation

Codecov / codecov/patch

nonebot_plugin_saa/registries/meta.py#L38-L40

Added lines #L38 - L40 were not covered by tests

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

Check warning on line 42 in nonebot_plugin_saa/registries/meta.py

View check run for this annotation

Codecov / codecov/patch

nonebot_plugin_saa/registries/meta.py#L42

Added line #L42 was not covered by tests

@classmethod
def _register_subclass(cls, fields) -> 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
cls._deserializer_dict[fields[cls._index_key].default] = cls
elif cls._level == Level.Normal:
pass
else:
raise RuntimeError("SerializationMeta init error")

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

@classmethod
def deserialize(cls, source: Any) -> Self:
if isinstance(source, str):
Expand All @@ -45,4 +63,4 @@ def deserialize(cls, source: Any) -> Self:

key = raw_obj.get(cls._index_key)
assert key
return cls._deserializer_dict[key].parse_obj(raw_obj)
return type_validate_python(cls._deserializer_dict[key], raw_obj)
14 changes: 11 additions & 3 deletions nonebot_plugin_saa/registries/platform_send_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from pydantic import BaseModel
from nonebot.params import Depends
from nonebot.adapters import Bot, Event
from nonebot.compat import PYDANTIC_V2, ConfigDict

from .meta import SerializationMeta
from ..utils import SupportedAdapters, SupportedPlatform, extract_adapter_type
Expand All @@ -31,9 +32,16 @@ class PlatformTarget(SerializationMeta):

platform_type: SupportedPlatform

class Config:
frozen = True
orm_mode = True
if PYDANTIC_V2:
model_config = ConfigDict(
frozen=True,
from_attributes=True,
)
else:

class Config:
frozen = True
orm_mode = True

Check warning on line 44 in nonebot_plugin_saa/registries/platform_send_target.py

View check run for this annotation

Codecov / codecov/patch

nonebot_plugin_saa/registries/platform_send_target.py#L42-L44

Added lines #L42 - L44 were not covered by tests

def arg_dict(self, bot: Bot):
adapter_type = extract_adapter_type(bot)
Expand Down
Loading

0 comments on commit 7d8f4ca

Please sign in to comment.