Skip to content

Commit

Permalink
⬆️ Update to pydantic 2.x
Browse files Browse the repository at this point in the history
  • Loading branch information
omg-xtao authored Nov 30, 2024
1 parent 4d9ff8f commit c92c184
Show file tree
Hide file tree
Showing 8 changed files with 33 additions and 35 deletions.
12 changes: 6 additions & 6 deletions enkanetwork/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def character(cls, id: Union[int, str]) -> Optional[assets.CharacterAsset]:
LOGGER.error(f"Character not found with id: {id}")
return

return assets.CharacterAsset.parse_obj({
return assets.CharacterAsset.model_validate({
"id": id if str(id).isdigit() else id.split("-")[0],
"skill_id": str(id).split("-")[1] if not str(id).isdigit() else 0,
"images": cls.create_character_icon(data["sideIconName"]),
Expand All @@ -80,7 +80,7 @@ def character_costume(cls, id: int) -> Optional[assets.CharacterCostume]:
LOGGER.error(f"Costume not found with id: {id}")
return

return assets.CharacterCostume.parse_obj({
return assets.CharacterCostume.model_validate({
"id": id,
"images": cls.create_chractar_costume_icon(data["sideIconName"])
})
Expand All @@ -104,7 +104,7 @@ def constellations(cls, id: int) -> Optional[assets.CharacterConstellationsAsset
LOGGER.error(f"Character constellations not found with id: {id}")
return

return assets.CharacterConstellationsAsset.parse_obj({
return assets.CharacterConstellationsAsset.model_validate({
"id": id,
**data,
"icon": utils.IconAsset(filename=data["icon"])
Expand All @@ -121,7 +121,7 @@ def skills(cls, id: int) -> Optional[assets.CharacterSkillAsset]:


pround = data.get("proudSkillGroupId", 0)
return assets.CharacterSkillAsset.parse_obj({
return assets.CharacterSkillAsset.model_validate({
"id": id,
**data,
"pround_map": pround if not pround is None and pround != "" else 0,
Expand All @@ -136,7 +136,7 @@ def namecards(cls, id: int) -> Optional[assets.NamecardAsset]:
LOGGER.error(f"Namecards not found with id: {id}")
return

return assets.NamecardAsset.parse_obj({
return assets.NamecardAsset.model_validate({
"id": id,
**data,
"icon": utils.IconAsset(filename=data["icon"]),
Expand All @@ -152,7 +152,7 @@ def artifact_props(cls, id: int):
LOGGER.error(f"Artifact props not found with id: {id}")
return

return assets.AritfactProps.parse_obj({
return assets.AritfactProps.model_validate({
"id": id,
**data
})
Expand Down
14 changes: 7 additions & 7 deletions enkanetwork/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ async def fetch_user_by_uid(
# Loda cache
cache = await self.__get_cache(uid)
if cache:
return EnkaNetworkResponse.parse_obj(cache)
return EnkaNetworkResponse.model_validate(cache)

data = await self.__http.fetch_user_by_uid(uid, info=info)
data = self.__format_json(data)
Expand All @@ -202,7 +202,7 @@ async def fetch_user_by_uid(
)
}

return EnkaNetworkResponse.parse_obj(data)
return EnkaNetworkResponse.model_validate(data)

async def fetch_user_by_username(
self,
Expand Down Expand Up @@ -236,7 +236,7 @@ async def fetch_user_by_username(
# Loda cache
cache = await self.__get_cache(profile_id)
if cache:
return EnkaNetworkProfileResponse.parse_obj(cache)
return EnkaNetworkProfileResponse.model_validate(cache)

data = await self.__http.fetch_user_by_username(profile_id)
data = self.__format_json(data)
Expand All @@ -252,7 +252,7 @@ async def fetch_user_by_username(
"hoyos": await self.fetch_hoyos_by_username(profile_id)
}

return EnkaNetworkProfileResponse.parse_obj(data)
return EnkaNetworkProfileResponse.model_validate(data)

async def fetch_hoyos_by_username(
self,
Expand Down Expand Up @@ -336,7 +336,7 @@ async def fetch_builds(
# Loda cache
cache = await self.__get_cache(key)
if cache:
return Builds.parse_obj(cache)
return Builds.model_validate(cache)

data = await self.__http.fetch_hoyos_by_username(
profile_id, metaname, True)
Expand All @@ -346,7 +346,7 @@ async def fetch_builds(
# Store cache
await self.__store_cache(key, data)

return Builds.parse_obj(data)
return Builds.model_validate(data)

async def fetch_raw_data(self, uid: Union[str, int], *, info: bool = False) -> Dict[str, Any]: # noqa
"""Fetches raw data for a user with the given UID. """
Expand Down Expand Up @@ -405,7 +405,7 @@ async def update_assets(self) -> None:
self.assets.reload_assets()

async def __format_hoyos(self, username: str, data: List[Any]) -> List[PlayerHoyos]: # noqa
return [PlayerHoyos.parse_obj({
return [PlayerHoyos.model_validate({
"builds": await self.fetch_builds(profile_id=username,
metaname=data[key]["hash"]),
**data[key]
Expand Down
12 changes: 8 additions & 4 deletions enkanetwork/model/assets.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pydantic import BaseModel, Field
from pydantic import ConfigDict, BaseModel, Field
from typing import List, Any

from ..enum import ElementType
Expand Down Expand Up @@ -37,6 +37,8 @@ class NamecardAsset(BaseModel):
banner: IconAsset
navbar: IconAsset

model_config = ConfigDict(coerce_numbers_to_str=True)


class CharacterIconAsset(BaseModel):
""" Character Icon (Assets)
Expand Down Expand Up @@ -77,6 +79,8 @@ class CharacterSkillAsset(BaseModel):
hash_id: str = Field("", alias="nameTextMapHash")
icon: IconAsset = None

model_config = ConfigDict(coerce_numbers_to_str=True)


class CharacterConstellationsAsset(BaseModel):
""" Character Constellations (Assets)
Expand All @@ -94,6 +98,8 @@ class CharacterConstellationsAsset(BaseModel):
hash_id: str = Field("", alias="nameTextMapHash")
icon: IconAsset = None

model_config = ConfigDict(coerce_numbers_to_str=True)


class CharacterCostume(BaseModel):
""" Character Costume (Assets)
Expand Down Expand Up @@ -147,9 +153,7 @@ class CharacterAsset(BaseModel):
skill_id: int = 0
skills: List[int] = []
constellations: List[int] = Field([], alias="talents")

class Config:
use_enum_values = True
model_config = ConfigDict(use_enum_values=True, coerce_numbers_to_str=True)

def __init__(self, **data: Any) -> None:
super().__init__(**data)
Expand Down
6 changes: 2 additions & 4 deletions enkanetwork/model/character.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging

from pydantic import BaseModel, Field
from pydantic import ConfigDict, BaseModel, Field
from typing import List, Any, Dict

from .equipments import Equipments
Expand Down Expand Up @@ -168,6 +168,4 @@ def __init__(self, **data: Any) -> None:

# Get name from hash map
self.name = _name

class Config:
use_enum_values = True
model_config = ConfigDict(use_enum_values=True)
16 changes: 6 additions & 10 deletions enkanetwork/model/equipments.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging

from pydantic import BaseModel, Field
from pydantic import ConfigDict, BaseModel, Field
from typing import Any, List, Union

from .utils import IconAsset
Expand Down Expand Up @@ -67,26 +67,24 @@ def __init__(self, **data: Any) -> None:
self.artifact_type = EquipType(data["equipType"])
# Sub Stats
for stats in data["reliquarySubstats"] if "reliquarySubstats" in data else []:
self.substats.append(EquipmentsStats.parse_obj(stats))
self.substats.append(EquipmentsStats.model_validate(stats))

if data["itemType"] == "ITEM_WEAPON": # AKA. Weapon
LOGGER.debug("=== Weapon ===")

# Main and Sub Stats
self.mainstats = EquipmentsStats.parse_obj(
self.mainstats = EquipmentsStats.model_validate(
data["weaponStats"][0])
for stats in data["weaponStats"][1:]:
self.substats.append(EquipmentsStats.parse_obj(stats))
self.substats.append(EquipmentsStats.model_validate(stats))

_name = Assets.get_hash_map(data.get("nameTextMapHash"))
if "setNameTextMapHash" in data:
_artifact_name_set = Assets.get_hash_map(str(data["setNameTextMapHash"]))
self.artifact_name_set = _artifact_name_set or ""

self.name = _name if _name is not None else ""

class Config:
use_enum_values = True
model_config = ConfigDict(use_enum_values=True)

class EquipmentsProps(BaseModel):
id: int = 0
Expand Down Expand Up @@ -128,9 +126,7 @@ class Equipments(BaseModel):
refinement: int = 1 # Refinement of equipments (Weapon only)
ascension: int = 0 # Ascension (Weapon only)
props: List[EquipmentsProps] = []

class Config:
use_enum_values = True
model_config = ConfigDict(use_enum_values=True)

def __init__(self, **data: Any) -> None:
data["flat"]["icon"] = IconAsset(filename=data["flat"]["icon"])
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pydantic<2
pydantic>=2.0.0,<3.0.0
aiohttp
cachetools
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"Operating System :: OS Independent",
],
install_requires=[
"pydantic",
"pydantic>=2.0.0,<3.0.0",
"aiohttp",
"cachetools"
],
Expand Down
4 changes: 2 additions & 2 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def test_artifacts() -> None:

for star in _j["artifacts"]:
raw = _j["artifacts"][star]
data = Equipments.parse_obj(raw)
data = Equipments.model_validate(raw)
assert data.id == raw["itemId"]
assert data.type in list(EquipmentsType)
assert data.detail.name is not None
Expand Down Expand Up @@ -106,7 +106,7 @@ def test_weapons():

for star in _j["weapons"]:
raw = _j["weapons"][star]
data = Equipments.parse_obj(raw)
data = Equipments.model_validate(raw)
assert data.id == raw["itemId"]
assert data.type in list(EquipmentsType)
assert data.detail.name is not None
Expand Down

0 comments on commit c92c184

Please sign in to comment.