Skip to content

Commit

Permalink
refactor: 定义更多内部常量,替代 Magic Number
Browse files Browse the repository at this point in the history
  • Loading branch information
FHU-yezi committed Jan 15, 2025
1 parent 46650c3 commit 4e9752a
Show file tree
Hide file tree
Showing 8 changed files with 33 additions and 23 deletions.
15 changes: 9 additions & 6 deletions jkit/article.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
TYPE_CHECKING,
Any,
Literal,
Optional,
)

from httpx import HTTPStatusError
Expand All @@ -25,7 +24,11 @@
normalize_percentage,
)
from jkit.config import CONFIG
from jkit.constants import BLANK_LINES_REGEX, HTML_TAG_REGEX
from jkit.constants import (
_BLANK_LINES_REGEX,
_HTML_TAG_REGEX,
_RESOURCE_UNAVAILABLE_STATUS_CODE,
)
from jkit.exceptions import ResourceUnavailableError
from jkit.identifier_check import is_article_slug
from jkit.identifier_convert import article_slug_to_url, article_url_to_slug
Expand Down Expand Up @@ -105,8 +108,8 @@ class ArticleInfo(DataObject, frozen=True):

@property
def text_content(self) -> str:
result = HTML_TAG_REGEX.sub("", self.html_content)
return BLANK_LINES_REGEX.sub("\n", result)
result = _HTML_TAG_REGEX.sub("", self.html_content)
return _BLANK_LINES_REGEX.sub("\n", result)


class ArticleAudioInfo(DataObject, frozen=True):
Expand Down Expand Up @@ -211,7 +214,7 @@ def __init__(
self,
*,
slug: str | None = None,
url: Optional[str] = None, # noqa: UP007
url: str | None = None,
) -> None:
super().__init__()

Expand All @@ -232,7 +235,7 @@ async def check(self) -> None:
)
self._checked = True
except HTTPStatusError as e:
if e.response.status_code == 404: # noqa: PLR2004
if e.response.status_code == _RESOURCE_UNAVAILABLE_STATUS_CODE:
raise ResourceUnavailableError(
f"文章 {self.url} 不存在或已被删除 / 私密 / 锁定"
) from None
Expand Down
3 changes: 2 additions & 1 deletion jkit/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from jkit._network_request import get_json
from jkit._normalization import normalize_assets_amount, normalize_datetime
from jkit.config import CONFIG
from jkit.constants import _RESOURCE_UNAVAILABLE_STATUS_CODE
from jkit.exceptions import ResourceUnavailableError
from jkit.identifier_check import is_collection_slug
from jkit.identifier_convert import collection_slug_to_url, collection_url_to_slug
Expand Down Expand Up @@ -124,7 +125,7 @@ async def check(self) -> None:
)
self._checked = True
except HTTPStatusError as e:
if e.response.status_code == 404: # noqa: PLR2004
if e.response.status_code == _RESOURCE_UNAVAILABLE_STATUS_CODE:
raise ResourceUnavailableError(
f"专题 {self.url} 不存在或已被删除"
) from None
Expand Down
15 changes: 9 additions & 6 deletions jkit/constants.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
from re import compile as regex_compile

HTML_TAG_REGEX = regex_compile("<.*?>")
BLANK_LINES_REGEX = regex_compile("\n{2,}")

JIANSHU_URL_REGEX = regex_compile(r"^https://www\.jianshu\.com/[a-zA-Z0-9/]*/?$")
USER_UPLOADED_URL_REGEX = regex_compile(r"^https?:\/\/.*/?$")
USER_URL_REGEX = regex_compile(
Expand All @@ -22,7 +19,13 @@
)
ISLAND_SLUG_REGEX = regex_compile(r"^[a-z0-9]{16}$")

NOTEBOOK_ID_MIN = 100000
NOTEBOOK_ID_MAX = 99999999

USER_NAME_REGEX = regex_compile(r"^[\w]{,15}$")

_HTML_TAG_REGEX = regex_compile("<.*?>")
_BLANK_LINES_REGEX = regex_compile("\n{2,}")

_NOTEBOOK_ID_MIN = 100000
_NOTEBOOK_ID_MAX = 99999999

_RESOURCE_UNAVAILABLE_STATUS_CODE = 404
_ASSETS_ACTION_FAILED_STATUS_CODE = 422
6 changes: 3 additions & 3 deletions jkit/identifier_check.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from jkit.constants import (
_NOTEBOOK_ID_MAX,
_NOTEBOOK_ID_MIN,
ARTICLE_SLUG_REGEX,
ARTICLE_URL_REGEX,
COLLECTION_SLUG_REGEX,
COLLECTION_URL_REGEX,
ISLAND_SLUG_REGEX,
ISLAND_URL_REGEX,
NOTEBOOK_ID_MAX,
NOTEBOOK_ID_MIN,
NOTEBOOK_URL_REGEX,
USER_SLUG_REGEX,
USER_URL_REGEX,
Expand Down Expand Up @@ -42,7 +42,7 @@ def is_article_slug(x: str, /) -> bool:


def is_notebook_id(x: int, /) -> bool:
return NOTEBOOK_ID_MIN <= x <= NOTEBOOK_ID_MAX
return _NOTEBOOK_ID_MIN <= x <= _NOTEBOOK_ID_MAX


def is_collection_slug(x: str, /) -> bool:
Expand Down
6 changes: 3 additions & 3 deletions jkit/msgspec_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
from msgspec import Meta

from jkit.constants import (
_NOTEBOOK_ID_MAX,
_NOTEBOOK_ID_MIN,
ARTICLE_SLUG_REGEX,
ARTICLE_URL_REGEX,
COLLECTION_SLUG_REGEX,
COLLECTION_URL_REGEX,
ISLAND_SLUG_REGEX,
ISLAND_URL_REGEX,
JIANSHU_URL_REGEX,
NOTEBOOK_ID_MAX,
NOTEBOOK_ID_MIN,
NOTEBOOK_URL_REGEX,
USER_NAME_REGEX,
USER_SLUG_REGEX,
Expand Down Expand Up @@ -40,6 +40,6 @@

UserSlug = Annotated[str, Meta(pattern=USER_SLUG_REGEX.pattern)]
ArticleSlug = Annotated[str, Meta(pattern=ARTICLE_SLUG_REGEX.pattern)]
NotebookId = Annotated[int, Meta(ge=NOTEBOOK_ID_MIN, le=NOTEBOOK_ID_MAX)]
NotebookId = Annotated[int, Meta(ge=_NOTEBOOK_ID_MIN, le=_NOTEBOOK_ID_MAX)]
CollectionSlug = Annotated[str, Meta(pattern=COLLECTION_SLUG_REGEX.pattern)]
IslandSlug = Annotated[str, Meta(pattern=ISLAND_SLUG_REGEX.pattern)]
3 changes: 2 additions & 1 deletion jkit/notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from jkit._network_request import get_json
from jkit._normalization import normalize_assets_amount, normalize_datetime
from jkit.config import CONFIG
from jkit.constants import _RESOURCE_UNAVAILABLE_STATUS_CODE
from jkit.exceptions import ResourceUnavailableError
from jkit.identifier_check import is_notebook_id
from jkit.identifier_convert import notebook_id_to_url
Expand Down Expand Up @@ -125,7 +126,7 @@ async def check(self) -> None:
)
self._checked = True
except HTTPStatusError as e:
if e.response.status_code == 404: # noqa: PLR2004
if e.response.status_code == _RESOURCE_UNAVAILABLE_STATUS_CODE:
raise ResourceUnavailableError(
f"文集 {self.url} 不存在或已被删除"
) from None
Expand Down
5 changes: 3 additions & 2 deletions jkit/private/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
normalize_percentage,
)
from jkit.config import CONFIG
from jkit.constants import _ASSETS_ACTION_FAILED_STATUS_CODE
from jkit.credential import JianshuCredential
from jkit.exceptions import BalanceNotEnoughError, WeeklyConvertLimitExceededError
from jkit.msgspec_constraints import (
Expand Down Expand Up @@ -294,7 +295,7 @@ async def fp_to_ftn(self, /, amount: int | float) -> None:
cookies=self._credential.cookies,
)
except HTTPStatusError as e:
if e.response.status_code == 422: # noqa: PLR2004
if e.response.status_code == _ASSETS_ACTION_FAILED_STATUS_CODE:
data = JSON_DECODER.decode(e.response.content)
if data["error"][0]["code"] == 18002: # noqa: PLR2004
raise BalanceNotEnoughError("简书钻余额不足") from None
Expand All @@ -320,7 +321,7 @@ async def ftn_to_fp(self, /, amount: int | float) -> None:
cookies=self._credential.cookies,
)
except HTTPStatusError as e:
if e.response.status_code == 422: # noqa: PLR2004
if e.response.status_code == _ASSETS_ACTION_FAILED_STATUS_CODE:
data = JSON_DECODER.decode(e.response.content)
if data["error"][0]["code"] == 18002: # noqa: PLR2004
raise BalanceNotEnoughError("简书贝余额不足") from None
Expand Down
3 changes: 2 additions & 1 deletion jkit/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from jkit._network_request import get_html, get_json
from jkit._normalization import normalize_assets_amount, normalize_datetime
from jkit.config import CONFIG
from jkit.constants import _RESOURCE_UNAVAILABLE_STATUS_CODE
from jkit.exceptions import APIUnsupportedError, ResourceUnavailableError
from jkit.identifier_check import is_user_slug
from jkit.identifier_convert import user_slug_to_url, user_url_to_slug
Expand Down Expand Up @@ -174,7 +175,7 @@ async def check(self) -> None:
path=f"/asimov/users/slug/{self.slug}",
)
except HTTPStatusError as e:
if e.response.status_code == 404: # noqa: PLR2004
if e.response.status_code == _RESOURCE_UNAVAILABLE_STATUS_CODE:
raise ResourceUnavailableError(
f"用户 {self.url} 不存在或已注销 / 被封禁"
) from None
Expand Down

0 comments on commit 4e9752a

Please sign in to comment.