适配 Pydantic V2

This commit is contained in:
2024-04-24 00:49:01 +08:00
parent 87c87ad231
commit 563564ac8d
5 changed files with 17 additions and 12 deletions

View File

@@ -30,7 +30,7 @@ class PydanticType(TypeDecorator):
if isinstance(value, str | bytes):
for i in self.get_model():
try:
return i.parse_raw(value)
return i.model_validate_json(value)
except ValidationError: # noqa: PERF203
...
raise TypeError

View File

@@ -1,8 +1,8 @@
from datetime import datetime, timezone
from aiocache import Cache as ACache # type: ignore[import-untyped]
from nonebot.compat import type_validate_json
from nonebot.log import logger
from pydantic import parse_raw_as
from ...utils.request import Request
from .schemas.base import FailedModel, SuccessModel
@@ -18,7 +18,7 @@ class Cache:
cached_data = await cls.cache.get(url)
if cached_data is None:
response_data = await Request.request(url)
parsed_data: SuccessModel | FailedModel = parse_raw_as(SuccessModel | FailedModel, response_data) # type: ignore[arg-type]
parsed_data: SuccessModel | FailedModel = type_validate_json(SuccessModel | FailedModel, response_data) # type: ignore[arg-type]
if isinstance(parsed_data, SuccessModel):
await cls.cache.add(
url,

View File

@@ -7,9 +7,9 @@ from statistics import mean
from typing import Literal
from nonebot import get_driver
from nonebot.compat import type_validate_json
from nonebot_plugin_apscheduler import scheduler # type: ignore[import-untyped]
from nonebot_plugin_orm import get_session
from pydantic import parse_raw_as
from sqlalchemy import select
from ...db import create_or_update_bind
@@ -96,7 +96,7 @@ class Processor(ProcessorMeta):
self.raw_response.user_info = await Cache.get(
splice_url([BASE_URL, 'users/', f'{self.user.ID or self.user.name}'])
)
user_info: UserInfo = parse_raw_as(UserInfo, self.raw_response.user_info) # type: ignore[arg-type]
user_info: UserInfo = type_validate_json(UserInfo, self.raw_response.user_info) # type: ignore[arg-type]
if isinstance(user_info, InfoFailed):
raise RequestError(f'用户信息请求错误:\n{user_info.error}')
self.processed_data.user_info = user_info
@@ -108,7 +108,7 @@ class Processor(ProcessorMeta):
self.raw_response.user_records = await Cache.get(
splice_url([BASE_URL, 'users/', f'{self.user.ID or self.user.name}/', 'records'])
)
user_records: UserRecords = parse_raw_as(UserRecords, self.raw_response.user_records) # type: ignore[arg-type]
user_records: UserRecords = type_validate_json(UserRecords, self.raw_response.user_records) # type: ignore[arg-type]
if isinstance(user_records, RecordsFailed):
raise RequestError(f'用户Solo数据请求错误:\n{user_records.error}')
self.processed_data.user_records = user_records
@@ -158,7 +158,10 @@ class Processor(ProcessorMeta):
@scheduler.scheduled_job('cron', hour='0,6,12,18', minute=0)
@retry(exception_type=RequestError, delay=timedelta(minutes=15))
async def get_io_rank_data() -> None:
league_all: LeagueAll = parse_raw_as(LeagueAll, await Cache.get(splice_url([BASE_URL, 'users/lists/league/all']))) # type: ignore[arg-type]
league_all: LeagueAll = type_validate_json(
LeagueAll, # type: ignore[arg-type]
await Cache.get(splice_url([BASE_URL, 'users/lists/league/all'])),
)
if isinstance(league_all, LeagueAllFailed):
raise RequestError(f'排行榜数据请求错误:\n{league_all.error}')

View File

@@ -3,8 +3,8 @@ from re import match
from typing import Literal
from urllib.parse import urlencode
from nonebot.compat import type_validate_json
from nonebot_plugin_orm import get_session
from pydantic import parse_raw_as
from ...db import create_or_update_bind
from ...utils.exception import MessageFormatError, RequestError
@@ -120,7 +120,7 @@ class Processor(ProcessorMeta):
]
)
self.raw_response.user_info = await Request.request(url)
user_info: UserInfo = parse_raw_as(UserInfo, self.raw_response.user_info) # type: ignore[arg-type]
user_info: UserInfo = type_validate_json(UserInfo, self.raw_response.user_info) # type: ignore[arg-type]
if not isinstance(user_info, InfoSuccess):
raise RequestError(f'用户信息请求错误:\n{user_info.error}')
self.processed_data.user_info = user_info
@@ -141,7 +141,9 @@ class Processor(ProcessorMeta):
]
)
)
self.processed_data.user_profile[params] = UserProfile.parse_raw(self.raw_response.user_profile[params])
self.processed_data.user_profile[params] = UserProfile.model_validate_json(
self.raw_response.user_profile[params]
)
return self.processed_data.user_profile[params]
async def get_game_data(self) -> GameData | None:

View File

@@ -3,7 +3,7 @@ from urllib.parse import urljoin, urlparse
from aiofiles import open
from httpx import AsyncClient, HTTPError
from nonebot import get_driver
from nonebot import get_driver, get_plugin_config
from nonebot.log import logger
from playwright.async_api import Response
from ujson import JSONDecodeError, dumps, loads
@@ -13,7 +13,7 @@ from .browser import BrowserManager
from .exception import RequestError
driver = get_driver()
config = Config.parse_obj(driver.config)
config = get_plugin_config(Config)
@driver.on_startup