Skip to content

Commit 2c50ae4

Browse files
authored
v2.1.17: 增加模块级别配置类,优化异常类型、代码示例 (#103)
1 parent 6948743 commit 2c50ae4

10 files changed

+63
-37
lines changed

src/jmcomic/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22
# 被依赖方 <--- 使用方
33
# config <--- entity <--- toolkit <--- client <--- option <--- downloader
44

5-
__version__ = '2.1.16'
5+
__version__ = '2.1.17'
66

77
from .api import *

src/jmcomic/jm_client_impl.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def get_jmcomic_domain_all(self, postman=None):
143143
def fallback(self, request, url, domain_index, retry_count, **kwargs):
144144
msg = f"请求重试全部失败: [{url}], {self.domain_list}"
145145
jm_debug('req.fallback', msg)
146-
raise AssertionError(msg)
146+
raise JmModuleConfig.exception(msg)
147147

148148

149149
# 基于网页实现的JmClient
@@ -216,7 +216,7 @@ def login(self,
216216
)
217217

218218
if resp.status_code != 301:
219-
raise AssertionError(f'登录失败,状态码为{resp.status_code}')
219+
raise JmModuleConfig.exception(f'登录失败,状态码为{resp.status_code}')
220220

221221
if refresh_client_cookies is True:
222222
self['cookies'] = resp.cookies
@@ -251,7 +251,7 @@ def raise_request_error(cls, resp, msg: Optional[str] = None):
251251
+ (f"响应文本=[{resp.text}]" if len(resp.text) < 200 else
252252
f'响应文本过长(len={len(resp.text)}),不打印'
253253
)
254-
raise AssertionError(msg)
254+
raise JmModuleConfig.exception(msg)
255255

256256
def get_jm_image(self, img_url) -> JmImageResp:
257257

src/jmcomic/jm_client_interface.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,13 @@ def model(self) -> DictModel:
2323
class JmImageResp(JmResp):
2424

2525
def json(self, **kwargs) -> Dict:
26-
raise AssertionError
26+
raise NotImplementedError
2727

2828
def require_success(self):
2929
if self.is_success:
3030
return
3131

32-
raise AssertionError(self.get_error_msg())
32+
raise JmModuleConfig.exception(self.get_error_msg())
3333

3434
def get_error_msg(self):
3535
msg = f'禁漫图片获取失败: [{self.url}]'
@@ -68,7 +68,7 @@ class JmApiResp(JmResp):
6868
@classmethod
6969
def wrap(cls, resp, key_ts):
7070
if isinstance(resp, JmApiResp):
71-
raise AssertionError('重复包装')
71+
raise JmModuleConfig.exception('重复包装')
7272

7373
return cls(resp, key_ts)
7474

src/jmcomic/jm_config.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@ def default_postman_constructor(session, **kwargs):
1818

1919

2020
def default_raise_regex_error(msg, *_args, **_kwargs):
21-
raise AssertionError(msg)
21+
raise JmModuleConfig.exception(msg)
22+
23+
24+
class JmcomicException(Exception):
25+
pass
2226

2327

2428
class JmModuleConfig:
@@ -60,7 +64,9 @@ class JmModuleConfig:
6064
CLASS_OPTION = None
6165
CLASS_ALBUM = None
6266
CLASS_PHOTO = None
67+
CLASS_IMAGE = None
6368
CLASS_CLIENT_IMPL = {}
69+
CLASS_EXCEPTION = None
6470

6571
# 执行debug的函数
6672
debug_executor = default_jm_debug
@@ -104,6 +110,14 @@ def photo_class(cls):
104110
from .jm_entity import JmPhotoDetail
105111
return JmPhotoDetail
106112

113+
@classmethod
114+
def image_class(cls):
115+
if cls.CLASS_IMAGE is not None:
116+
return cls.CLASS_IMAGE
117+
118+
from .jm_entity import JmImageDetail
119+
return JmImageDetail
120+
107121
@classmethod
108122
def client_impl_class(cls, client_key: str):
109123
client_impl_dict = cls.CLASS_CLIENT_IMPL
@@ -114,6 +128,13 @@ def client_impl_class(cls, client_key: str):
114128

115129
return impl_class
116130

131+
@classmethod
132+
def exception(cls, msg: str):
133+
if cls.CLASS_EXCEPTION is not None:
134+
return cls.CLASS_EXCEPTION(msg)
135+
136+
return JmcomicException(msg)
137+
117138
@classmethod
118139
@field_cache("DOMAIN")
119140
def domain(cls, postman=None):
@@ -185,7 +206,7 @@ def get_jmcomic_domain_all(cls, postman=None):
185206

186207
resp = postman.get(cls.JM_PUB_URL)
187208
if resp.status_code != 200:
188-
raise AssertionError(resp.text)
209+
raise JmModuleConfig.exception(resp.text)
189210

190211
from .jm_toolkit import JmcomicText
191212
domain_list = JmcomicText.analyse_jm_pub_html(resp.text)

src/jmcomic/jm_entity.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -241,11 +241,11 @@ def create_image_detail(self, index) -> JmImageDetail:
241241
# 校验参数
242242
length = len(self.page_arr)
243243
if index >= length:
244-
raise AssertionError(f'创建JmImageDetail失败,{index} >= {length}')
244+
raise JmModuleConfig.exception(f'创建JmImageDetail失败,{index} >= {length}')
245245

246246
data_original = self.get_img_data_original(self.page_arr[index])
247247

248-
return JmImageDetail.of(
248+
return JmModuleConfig.image_class().of(
249249
self.photo_id,
250250
self.scramble_id,
251251
data_original,
@@ -262,7 +262,7 @@ def get_img_data_original(self, img_name: str) -> str:
262262
"""
263263
data_original_domain = self.data_original_domain
264264
if data_original_domain is None:
265-
raise AssertionError(f'图片域名为空: {self.__dict__}')
265+
raise JmModuleConfig.exception(f'图片域名为空: {self.__dict__}')
266266

267267
return f'https://{data_original_domain}/media/photos/{self.photo_id}/{img_name}'
268268

@@ -330,13 +330,13 @@ def create_photo_detail(self, index) -> Tuple[JmPhotoDetail, Tuple]:
330330
length = len(self.episode_list)
331331

332332
if index >= length:
333-
raise AssertionError(f'创建JmPhotoDetail失败,{index} >= {length}')
333+
raise JmModuleConfig.exception(f'创建JmPhotoDetail失败,{index} >= {length}')
334334

335335
# episode_info: ('212214', '81', '94 突然打來', '2020-08-29')
336336
episode_info: tuple = self.episode_list[index]
337337
photo_id, photo_index, photo_title, photo_pub_date = episode_info
338338

339-
photo = JmPhotoDetail(
339+
photo = JmModuleConfig.photo_class()(
340340
photo_id=photo_id,
341341
scramble_id=self.scramble_id,
342342
title=photo_title,

src/jmcomic/jm_option.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ class DirRule:
1010
# 根目录 / Photo-序号&标题 /
1111
'Bd_Pindextitle',
1212
# 根目录 / Photo-自定义类属性 /
13-
'Bd_Aauthor_Atitle_Pcustomfield', # 使用自定义类属性前,需替换 JmcomicText的 PhotoClass / AlbumClass
13+
'Bd_Aauthor_Atitle_Pcustomfield',
14+
# 需要替换JmModuleConfig.CLASS_ALBUM / CLASS_PHOTO才能让自定义属性生效
1415
]
1516

1617
RuleFunc = Callable[[Union[JmAlbumDetail, JmPhotoDetail, None]], str]
@@ -45,8 +46,10 @@ def choose_param(key):
4546
path_ls.append(str(ret))
4647
except BaseException as e:
4748
# noinspection PyUnboundLocalVariable
48-
raise AssertionError(f'路径规则"{self.rule_dsl}"的第{i + 1}个解析出错: {e},'
49-
f'param is {param}')
49+
raise JmModuleConfig.exception(
50+
f'路径规则"{self.rule_dsl}"的第{i + 1}个解析出错: {e},'
51+
f'param is {param}'
52+
)
5053

5154
return fix_filepath('/'.join(path_ls), is_dir=True)
5255

@@ -214,7 +217,7 @@ def to_file(self, filepath=None):
214217
filepath = self.filepath
215218

216219
if filepath is None:
217-
raise AssertionError("未指定JmOption的保存路径")
220+
raise JmModuleConfig.exception("未指定JmOption的保存路径")
218221

219222
PackerUtil.pack(self.deconstruct(), filepath)
220223

src/jmcomic/jm_toolkit.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,15 @@ def parse_to_photo_id(cls, text) -> str:
5252
return str(text)
5353

5454
if not isinstance(text, str):
55-
raise AssertionError(f"无法解析jm车号, 参数类型为: {type(text)}")
55+
raise JmModuleConfig.exception(f"无法解析jm车号, 参数类型为: {type(text)}")
5656

5757
# 43210
5858
if text.isdigit():
5959
return text
6060

6161
# Jm43210
6262
if len(text) <= 2:
63-
raise AssertionError(f"无法解析jm车号, 文本为: {text}")
63+
raise JmModuleConfig.exception(f"无法解析jm车号, 文本为: {text}")
6464

6565
# text: JM12341
6666
c0 = text[0]
@@ -72,7 +72,7 @@ def parse_to_photo_id(cls, text) -> str:
7272
# https://xxx/photo/412038
7373
match = cls.pattern_jm_pa_id.search(text)
7474
if match is None:
75-
raise AssertionError(f"无法解析jm车号, 文本为: {text}")
75+
raise JmModuleConfig.exception(f"无法解析jm车号, 文本为: {text}")
7676
return match[2]
7777

7878
@classmethod

tests/test_jmcomic/test_jm_client.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,9 @@ def test_gt_300_photo(self):
5252
self.client.download_by_image_detail(image, workspace('3000.png'))
5353

5454
def test_album_missing(self):
55+
JmModuleConfig.CLASS_EXCEPTION = JmcomicException
5556
self.assertRaises(
56-
AssertionError,
57+
JmcomicException,
5758
self.client.get_album_detail,
5859
'332583'
5960
)

usage/usage_feature_filter.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,27 @@ def filter_iter_objs(self, iter_objs: DownloadIterObjs):
1919
** 本文件下面的示例只演示步骤1 **
2020
2121
本文件包含如下示例:
22-
- 只下载本子的特定章节以后的章节
2322
- 只下载章节的前三张图
23+
- 只下载本子的特定章节以后的章节
2424
2525
2626
"""
2727

2828
from jmcomic import *
2929

3030

31+
# 示例:只下载章节的前三张图
32+
class First3ImageDownloader(JmDownloader):
33+
34+
def filter_iter_objs(self, iter_objs: DownloadIterObjs):
35+
if isinstance(iter_objs, JmPhotoDetail):
36+
photo: JmPhotoDetail = iter_objs
37+
# 支持[start,end,step]
38+
return photo[:3]
39+
40+
return iter_objs
41+
42+
3143
# 示例:只下载本子的特定章节以后的章节
3244
# 参考:https://github.com/hect0x7/JMComic-Crawler-Python/issues/95
3345
class FindUpdateDownloader(JmDownloader):
@@ -58,15 +70,3 @@ def find_update(self, album: JmAlbumDetail):
5870
is_new_photo = True
5971

6072
return photo_ls
61-
62-
63-
# 示例:只下载章节的前三张图
64-
class First3ImageDownloader(JmDownloader):
65-
66-
def filter_iter_objs(self, iter_objs: DownloadIterObjs):
67-
if isinstance(iter_objs, JmPhotoDetail):
68-
photo: JmPhotoDetail = iter_objs
69-
# 支持[start,end,step]
70-
return photo[:3]
71-
72-
return iter_objs

usage/usage_simple.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010

1111
from jmcomic import *
1212

13+
# 核心下载配置
1314
option = create_option(
1415
f'你的配置文件路径,例如: D:/a/b/c/jmcomic/config.yml'
1516
)
17+
# 提供请求功能的客户端对象
1618
client = option.build_jm_client()
1719

1820

@@ -24,8 +26,7 @@ def download_jm_album():
2426
2527
''')
2628

27-
download_album(ls, option) # 效果同下面的代码
28-
# download_album_batch(ls, op)
29+
download_album(ls, option)
2930

3031

3132
@timeit('获取实体类: ')

0 commit comments

Comments
 (0)