Skip to content

Commit

Permalink
Do mass find and replace
Browse files Browse the repository at this point in the history
  • Loading branch information
seriaati committed Sep 19, 2024
1 parent 99d99fb commit dc9662d
Show file tree
Hide file tree
Showing 36 changed files with 186 additions and 372 deletions.
6 changes: 3 additions & 3 deletions genshin/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ async def honkai_stats(client: genshin.Client, uid: int) -> None:
data = await client.get_honkai_user(uid)

click.secho("Stats:", fg="yellow")
for k, v in data.stats.dict().items():
for k, v in data.stats.model_dump().items():
if isinstance(v, dict):
click.echo(f"{k}:")
for nested_k, nested_v in typing.cast("typing.Dict[str, object]", v).items():
Expand All @@ -102,7 +102,7 @@ async def genshin_stats(client: genshin.Client, uid: int) -> None:
data = await client.get_partial_genshin_user(uid)

click.secho("Stats:", fg="yellow")
for k, v in data.stats.dict().items():
for k, v in data.stats.model_dump().items():
value = click.style(str(v), bold=True)
click.echo(f"{k}: {value}")

Expand Down Expand Up @@ -335,7 +335,7 @@ async def login(account: str, password: str, port: int) -> None:
"""Login with a password."""
client = genshin.Client()
result = await client.os_login_with_password(account, password, port=port)
cookies = await genshin.complete_cookies(result.dict())
cookies = await genshin.complete_cookies(result.model_dump())

base: http.cookies.BaseCookie[str] = http.cookies.BaseCookie(cookies)
click.echo(f"Your cookies are: {click.style(base.output(header='', sep=';'), bold=True)}")
Expand Down
2 changes: 1 addition & 1 deletion genshin/client/components/auth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ async def verify_mmt(self, mmt_result: MMTResult) -> None:
**auth_utility.CREATE_MMT_HEADERS[self.region],
}

body = mmt_result.dict()
body = mmt_result.model_dump()
body["app_key"] = constants.GEETEST_RECORD_KEYS[self.default_game]

assert isinstance(self.cookie_manager, managers.CookieManager)
Expand Down
2 changes: 1 addition & 1 deletion genshin/client/components/auth/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ async def gt(request: web.Request) -> web.StreamResponse:

@routes.get("/mmt")
async def mmt_endpoint(request: web.Request) -> web.Response:
return web.json_response(mmt.dict() if mmt else {})
return web.json_response(mmt.model_dump() if mmt else {})

@routes.post("/send-data")
async def send_data_endpoint(request: web.Request) -> web.Response:
Expand Down
2 changes: 1 addition & 1 deletion genshin/client/components/chronicle/genshin.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ async def get_full_genshin_user(
)
abyss = models.SpiralAbyssPair(current=abyss1, previous=abyss2)

return models.FullGenshinUserStats(**user.dict(by_alias=True), abyss=abyss, activities=activities)
return models.FullGenshinUserStats(**user.model_dump(by_alias=True), abyss=abyss, activities=activities)

async def set_top_genshin_characters(
self,
Expand Down
2 changes: 1 addition & 1 deletion genshin/client/components/chronicle/honkai.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ async def get_full_honkai_user(
)

return models.FullHonkaiUserStats(
**user.dict(by_alias=True),
**user.model_dump(by_alias=True),
battlesuits=battlesuits,
abyss=abyss,
memorial_arena=mr,
Expand Down
16 changes: 5 additions & 11 deletions genshin/models/auth/cookie.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,7 @@

import typing

if typing.TYPE_CHECKING:
import pydantic.v1 as pydantic
else:
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic
import pydantic

__all__ = [
"AppLoginResult",
Expand All @@ -31,7 +25,7 @@ class StokenResult(pydantic.BaseModel):
mid: str
token: str

@pydantic.root_validator(pre=True)
@pydantic.model_validator(mode="before")
def _transform_result(cls, values: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]:
return {
"aid": values["user_info"]["aid"],
Expand All @@ -45,11 +39,11 @@ class CookieLoginResult(pydantic.BaseModel):

def to_str(self) -> str:
"""Convert the login cookies to a string."""
return "; ".join(f"{key}={value}" for key, value in self.dict().items())
return "; ".join(f"{key}={value}" for key, value in self.model_dump().items())

def to_dict(self) -> typing.Dict[str, str]:
"""Convert the login cookies to a dictionary."""
return self.dict()
return self.model_dump()


class QRLoginResult(CookieLoginResult):
Expand Down Expand Up @@ -126,7 +120,7 @@ class DeviceGrantResult(pydantic.BaseModel):
game_token: str
login_ticket: typing.Optional[str] = None

@pydantic.root_validator(pre=True)
@pydantic.model_validator(mode="before")
def _str_to_none(cls, data: typing.Dict[str, typing.Union[str, None]]) -> typing.Dict[str, typing.Union[str, None]]:
"""Convert empty strings to `None`."""
for key in data:
Expand Down
18 changes: 6 additions & 12 deletions genshin/models/auth/geetest.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,7 @@
import json
import typing

if typing.TYPE_CHECKING:
import pydantic.v1 as pydantic
else:
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic
import pydantic

from genshin.utility import auth as auth_utility

Expand All @@ -37,7 +31,7 @@ class BaseMMT(pydantic.BaseModel):
new_captcha: int
success: int

@pydantic.root_validator(pre=True)
@pydantic.model_validator(mode="before")
def __parse_data(cls, data: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]:
"""Parse the data if it was provided in a raw format."""
if "data" in data:
Expand Down Expand Up @@ -66,7 +60,7 @@ class SessionMMT(MMT):

def get_mmt(self) -> MMT:
"""Get the base MMT data."""
return MMT(**self.dict(exclude={"session_id"}))
return MMT(**self.model_dump(exclude={"session_id"}))


class MMTv4(BaseMMT):
Expand All @@ -83,7 +77,7 @@ class SessionMMTv4(MMTv4):

def get_mmt(self) -> MMTv4:
"""Get the base MMTv4 data."""
return MMTv4(**self.dict(exclude={"session_id"}))
return MMTv4(**self.model_dump(exclude={"session_id"}))


class RiskyCheckMMT(MMT):
Expand All @@ -100,7 +94,7 @@ def get_data(self) -> typing.Dict[str, typing.Any]:
This method acts as `dict` but excludes the `session_id` field.
"""
return self.dict(exclude={"session_id"})
return self.model_dump(exclude={"session_id"})


class BaseSessionMMTResult(BaseMMTResult):
Expand Down Expand Up @@ -170,4 +164,4 @@ def to_mmt(self) -> RiskyCheckMMT:
if self.mmt is None:
raise ValueError("The check result does not contain a MMT object.")

return RiskyCheckMMT(**self.mmt.dict(), check_id=self.id)
return RiskyCheckMMT(**self.mmt.model_dump(), check_id=self.id)
11 changes: 2 additions & 9 deletions genshin/models/auth/qrcode.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
"""Miyoushe QR Code Models"""

import enum
import typing

if typing.TYPE_CHECKING:
import pydantic.v1 as pydantic
else:
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic

import pydantic

__all__ = ["QRCodeCreationResult", "QRCodeStatus"]

Expand Down
8 changes: 1 addition & 7 deletions genshin/models/auth/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,7 @@

import typing

if typing.TYPE_CHECKING:
import pydantic.v1 as pydantic
else:
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic
import pydantic

__all__ = ["Account", "ShieldLoginResponse"]

Expand Down
12 changes: 3 additions & 9 deletions genshin/models/auth/verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,7 @@
import json
import typing

if typing.TYPE_CHECKING:
import pydantic.v1 as pydantic
else:
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic
import pydantic

__all__ = [
"ActionTicket",
Expand All @@ -30,7 +24,7 @@ class ActionTicket(pydantic.BaseModel):
risk_ticket: str
verify_str: VerifyStrategy

@pydantic.root_validator(pre=True)
@pydantic.model_validator(mode="before")
def __parse_data(cls, data: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]:
"""Parse the data if it was provided in a raw format."""
verify_str = data["verify_str"]
Expand All @@ -41,6 +35,6 @@ def __parse_data(cls, data: typing.Dict[str, typing.Any]) -> typing.Dict[str, ty

def to_rpc_verify_header(self) -> str:
"""Convert the action ticket to `x-rpc-verify` header."""
ticket = self.dict()
ticket = self.model_dump()
ticket["verify_str"] = json.dumps(ticket["verify_str"])
return json.dumps(ticket)
18 changes: 6 additions & 12 deletions genshin/models/genshin/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,7 @@
import collections
import typing

if typing.TYPE_CHECKING:
import pydantic.v1 as pydantic
else:
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic
import pydantic

from genshin.models.model import Aliased, APIModel, Unique

Expand Down Expand Up @@ -67,14 +61,14 @@ class CalculatorCharacter(character.BaseCharacter):
level: int = Aliased("level_current", default=0)
max_level: int

@pydantic.validator("element", pre=True)
@pydantic.field_validator("element", mode="before")
def __parse_element(cls, v: typing.Any) -> str:
if isinstance(v, str):
return v

return CALCULATOR_ELEMENTS[int(v)]

@pydantic.validator("weapon_type", pre=True)
@pydantic.field_validator("weapon_type", mode="before")
def __parse_weapon_type(cls, v: typing.Any) -> str:
if isinstance(v, str):
return v
Expand All @@ -93,7 +87,7 @@ class CalculatorWeapon(APIModel, Unique):
level: int = Aliased("level_current", default=0)
max_level: int

@pydantic.validator("type", pre=True)
@pydantic.field_validator("type", mode="before")
def __parse_weapon_type(cls, v: typing.Any) -> str:
if isinstance(v, str):
return v
Expand Down Expand Up @@ -184,14 +178,14 @@ class CalculatorCharacterDetails(APIModel):
talents: typing.Sequence[CalculatorTalent] = Aliased("skill_list")
artifacts: typing.Sequence[CalculatorArtifact] = Aliased("reliquary_list")

@pydantic.validator("talents")
@pydantic.field_validator("talents")
def __correct_talent_current_level(cls, v: typing.Sequence[CalculatorTalent]) -> typing.Sequence[CalculatorTalent]:
# passive talent have current levels at 0 for some reason
talents: typing.List[CalculatorTalent] = []

for talent in v:
if talent.max_level == 1 and talent.level == 0:
raw = talent.dict()
raw = talent.model_dump()
raw["level"] = 1
talent = CalculatorTalent(**raw)

Expand Down
18 changes: 6 additions & 12 deletions genshin/models/genshin/character.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,10 @@
import re
import typing

from genshin.utility import deprecation

if typing.TYPE_CHECKING:
import pydantic.v1 as pydantic
else:
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic
import pydantic

from genshin.models.model import APIModel, Unique
from genshin.utility import deprecation

from . import constants

Expand Down Expand Up @@ -136,11 +129,12 @@ class BaseCharacter(APIModel, Unique):

collab: bool = False

@pydantic.root_validator(pre=True)
@pydantic.model_validator(mode="before")
def __autocomplete(cls, values: typing.Dict[str, typing.Any]) -> typing.Dict[str, typing.Any]:
"""Complete missing data."""
all_fields = list(cls.__fields__.keys())
all_aliases = {f: cls.__fields__[f].alias for f in all_fields if cls.__fields__[f].alias}
all_fields = list(cls.model_fields.keys())
all_aliases = {f: cls.model_fields[f].alias for f in all_fields if cls.model_fields[f].alias}
all_aliases = {k: v for k, v in all_aliases.items() if v is not None}
# If the field is aliased, it may have a different key name in 'values',
# so we need to get the correct key name from the alias

Expand Down
12 changes: 3 additions & 9 deletions genshin/models/genshin/chronicle/abyss.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import datetime
import typing

if typing.TYPE_CHECKING:
import pydantic.v1 as pydantic
else:
try:
import pydantic.v1 as pydantic
except ImportError:
import pydantic
import pydantic

from genshin.constants import CN_TIMEZONE
from genshin.models.genshin import character
Expand Down Expand Up @@ -98,13 +92,13 @@ class SpiralAbyss(APIModel):

floors: typing.Sequence[Floor]

@pydantic.root_validator(pre=True)
@pydantic.model_validator(mode="before")
def __nest_ranks(cls, values: typing.Dict[str, typing.Any]) -> typing.Dict[str, AbyssCharacter]:
"""By default ranks are for some reason on the same level as the rest of the abyss."""
values.setdefault("ranks", {}).update(values)
return values

@pydantic.validator("start_time", "end_time", pre=True)
@pydantic.field_validator("start_time", "end_time", mode="before")
def __parse_timezones(cls, value: str) -> datetime.datetime:
return datetime.datetime.fromtimestamp(int(value), tz=CN_TIMEZONE)

Expand Down
Loading

0 comments on commit dc9662d

Please sign in to comment.