Skip to content
This repository has been archived by the owner on Aug 23, 2024. It is now read-only.

Commit

Permalink
feat: Add new exception and little bi format code
Browse files Browse the repository at this point in the history
  • Loading branch information
kuronekouwu committed Aug 14, 2023
1 parent 227ae22 commit 7b0e7d2
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 70 deletions.
54 changes: 31 additions & 23 deletions enkanetwork/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,20 @@


class EnkaNetworkAPI:
""" A library for API wrapper player by UID / Username from https://enka.network
"""
A library for API wrapper player by UID / Username
from https://enka.network
Parameters
------------
lang: :class:`str`
Init default language
debug: :class:`bool`
If set to `True`. In request data or get assets. It's will be shown log processing
If set to `True`. In request data or get assets.
It's will be shown log processing
key: :class:`str`
Depercated
Depercated
cache: :class:`bool`
If set to `True`. In response data will be cache data
user_agent: :class:`str`
Expand All @@ -54,7 +58,7 @@ class EnkaNetworkAPI:
http: :class:`HTTPClient`
HTTP for request and handle data
lang: :class:`Language`
A default language
A default language
Example
------------
Expand Down Expand Up @@ -175,19 +179,19 @@ async def fetch_user_by_uid(
The response player data
"""

# Loda cache
# Loda cache
cache = await self.__get_cache(uid)
if cache:
return EnkaNetworkResponse.parse_obj(cache)

data = await self.__http.fetch_user_by_uid(uid, info=info)
data = self.__format_json(data)

# Return data
self.LOGGER.debug("Parsing data...")

# Store cache
await self.__store_cache(uid,data)
await self.__store_cache(uid, data)

if "owner" in data:
data["owner"] = {
Expand Down Expand Up @@ -229,7 +233,7 @@ async def fetch_user_by_username(
:class:`EnkaNetworkProfileResponse`
The response profile / hoyos and builds data
"""
# Loda cache
# Loda cache
cache = await self.__get_cache(profile_id)
if cache:
return EnkaNetworkProfileResponse.parse_obj(cache)
Expand All @@ -240,7 +244,7 @@ async def fetch_user_by_username(
self.LOGGER.debug("Parsing data...")

# Store cache
await self.__store_cache(profile_id,data)
await self.__store_cache(profile_id, data)

# Fetch hoyos and build(s)
data = {
Expand Down Expand Up @@ -281,7 +285,7 @@ async def fetch_hoyos_by_username(
"""
key = profile_id + ":hoyos"

# Loda cache
# Loda cache
cache = await self.__get_cache(key)
if cache:
return self.__format_hoyos(profile_id, cache)
Expand All @@ -308,7 +312,7 @@ async def fetch_builds(
profile_id: Optional[:class:`str`]
Username / patreon ID has subscriptions in Enka.Network
metaname: Optional[:class:`str`]
Metaname from hoyos data or owner tag in hash field
Metaname from hoyos data or owner tag in hash field
Raises
------------
Expand All @@ -329,12 +333,13 @@ async def fetch_builds(
A response builds data
"""
key = profile_id + ":hoyos:" + metaname + ":builds"
# Loda cache
# Loda cache
cache = await self.__get_cache(key)
if cache:
return Builds.parse_obj(cache)

data = await self.__http.fetch_hoyos_by_username(profile_id, metaname, True)
data = await self.__http.fetch_hoyos_by_username(
profile_id, metaname, True)
data = self.__format_json(data)
self.LOGGER.debug("Parsing data...")

Expand All @@ -343,24 +348,24 @@ async def fetch_builds(

return Builds.parse_obj(data)

async def fetch_raw_data(self, uid: Union[str, int], *, info: bool = False) -> Dict[str, Any]:
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. """

# Loda cache
# Loda cache
cache = await self.__get_cache(uid)
if cache:
return cache

data = await self.__http.fetch_user_by_uid(uid, info=info)
data = self.__format_json(data)

# Store cache
await self.__store_cache(uid,data, cache=cache)
await self.__store_cache(uid, data, cache=cache)

return data

async def sync_build(self, uid: Union[str, int], old_data: Dict[str, Any]) -> Dict[str, Any]:
""" Sync build data
async def sync_build(self, uid: Union[str, int], old_data: Dict[str, Any]) -> Dict[str, Any]: # noqa
""" Sync build data
Parameters
----------
Expand Down Expand Up @@ -391,16 +396,18 @@ async def update_assets(self) -> None:
self.LOGGER.debug(f"Writing {folder} file {filename}...")

# dumps to json file
with open(os.path.join(path[folder], filename), "w", encoding="utf-8") as f:
with open(os.path.join(path[folder], filename), "w",
encoding="utf-8") as f:
json.dump(json.loads(data["content"]),
f, ensure_ascii=False, indent=4)

# Reload config
self.assets.reload_assets()

async def __format_hoyos(self, username: str, data: List[Any]) -> List[PlayerHoyos]:
async def __format_hoyos(self, username: str, data: List[Any]) -> List[PlayerHoyos]: # noqa
return [PlayerHoyos.parse_obj({
"builds": await self.fetch_builds(profile_id=username, metaname=data[key]["hash"]),
"builds": await self.fetch_builds(profile_id=username,
metaname=data[key]["hash"]),
**data[key]
}) for key in data]

Expand Down Expand Up @@ -430,7 +437,8 @@ async def __store_cache(self, key: str, data: Any, *, cache: Any = None):
if cache is None:
await Config.CACHE.set(key, data)
else:
await Config.CACHE.set(key, await self.merge_raw_data(data, cache_data=cache))
await Config.CACHE.set(key, await self.merge_raw_data(data,
cache_data=cache)) # noqa

# Concept by genshin.py python library
fetch_user = fetch_user_by_uid
Expand Down
69 changes: 51 additions & 18 deletions enkanetwork/exception.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,71 @@
"""
System exception
"""


class VaildateUIDError(Exception):
""" Raised when the UID is not valid. """

class ProfileNotFounded(Exception):
""" Raised when the profile is not found. """

class BuildNotPublicData(Exception):
""" Raised when the profile hoyos has public to hidden """
"""
EnkaNetwork network exception
"""

class HTTPException(Exception):
""" Exception that's raised when an HTTP request operation fails. """

class EnkaValidateFailed(HTTPException):
""" Exception that's raised for when status code 400 occurs."""
class EnkaNetworError(Exception):
"""Base class for EnkaNetwork errors."""

class EnkaPlayerNotFound(Exception):
""" Raised when the UID is not found. """

class EnkaServerError(HTTPException):
class NetworkError(EnkaNetworError):
"""Base class for exceptions due to networking errors."""


class TimedOut(NetworkError):
"""Raised when a request took too long to finish."""


class EnkaServerError(EnkaNetworError):
""" Exception that's raised for when status code 500 occurs."""

class EnkaServerMaintanance(HTTPException):

class EnkaServerMaintanance(EnkaNetworError):
""" Exception that's raised when status code 424 occurs. """

class EnkaServerRateLimit(HTTPException):

class EnkaServerRateLimit(EnkaNetworError):
""" Exception that's raised when status code 429 occurs."""

class EnkaServerUnknown(HTTPException):

class EnkaServerUnknown(EnkaNetworError):
""" Exception that's raised when status code 503 occurs. """


"""
EnkaNetwork response error
"""


class ProfileNotFounded(Exception):
""" Raised when the profile is not found. """


class BuildNotPublicData(Exception):
""" Raised when the profile hoyos has public to hidden """


class EnkaValidateFailed(EnkaNetworError):
""" Exception that's raised for when status code 400 occurs."""


class EnkaPlayerNotFound(Exception):
""" Raised when the UID is not found. """


ERROR_ENKA = {
400: [VaildateUIDError, "Validate UID {uid} failed."],
404: [EnkaPlayerNotFound, "Player ID {uid} not found. Please check your UID / Username"],
404: [EnkaPlayerNotFound, "Player ID {uid} not found. Please check your UID / Username"], # noqa
429: [EnkaServerRateLimit, "Enka.network has been rate limit this path"],
424: [EnkaServerMaintanance, "Enka.Network doing maintenance server. Please wait took 5-8 hours or 1 day"],
500: [EnkaServerError, "Enka.network server has down or Genshin server broken."],
424: [EnkaServerMaintanance, "Enka.Network doing maintenance server. Please wait took 5-8 hours or 1 day"], # noqa
500: [EnkaServerError, "Enka.network server has down or Genshin server broken."], # noqa
503: [EnkaServerUnknown, "I screwed up massively"]
}
}
Loading

0 comments on commit 7b0e7d2

Please sign in to comment.