ErisPulse 2.1.13rc3__py3-none-any.whl → 2.1.14a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ErisPulse/Core/__init__.py +8 -6
- ErisPulse/Core/adapter.py +18 -15
- ErisPulse/Core/config.py +0 -98
- ErisPulse/Core/env.py +1 -32
- ErisPulse/Core/erispulse_config.py +105 -0
- ErisPulse/Core/exceptions.py +108 -0
- ErisPulse/Core/logger.py +74 -1
- ErisPulse/Core/{server.py → router.py} +51 -70
- ErisPulse/__init__.py +21 -9
- ErisPulse/__main__.py +32 -21
- {erispulse-2.1.13rc3.dist-info → erispulse-2.1.14a1.dist-info}/METADATA +1 -1
- erispulse-2.1.14a1.dist-info/RECORD +16 -0
- ErisPulse/Core/raiserr.py +0 -181
- ErisPulse/Core/util.py +0 -123
- erispulse-2.1.13rc3.dist-info/RECORD +0 -16
- {erispulse-2.1.13rc3.dist-info → erispulse-2.1.14a1.dist-info}/WHEEL +0 -0
- {erispulse-2.1.13rc3.dist-info → erispulse-2.1.14a1.dist-info}/entry_points.txt +0 -0
- {erispulse-2.1.13rc3.dist-info → erispulse-2.1.14a1.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
# router.py (新文件名)
|
|
1
2
|
"""
|
|
2
|
-
ErisPulse
|
|
3
|
-
|
|
3
|
+
ErisPulse 路由系统
|
|
4
|
+
|
|
5
|
+
提供统一的HTTP和WebSocket路由管理,支持多适配器路由注册和生命周期管理。
|
|
4
6
|
|
|
5
7
|
{!--< tips >!--}
|
|
6
8
|
1. 适配器只需注册路由,无需自行管理服务器
|
|
@@ -19,9 +21,9 @@ from hypercorn.config import Config
|
|
|
19
21
|
from hypercorn.asyncio import serve
|
|
20
22
|
|
|
21
23
|
|
|
22
|
-
class
|
|
24
|
+
class RouterManager:
|
|
23
25
|
"""
|
|
24
|
-
|
|
26
|
+
路由管理器
|
|
25
27
|
|
|
26
28
|
{!--< tips >!--}
|
|
27
29
|
核心功能:
|
|
@@ -33,18 +35,18 @@ class AdapterServer:
|
|
|
33
35
|
|
|
34
36
|
def __init__(self):
|
|
35
37
|
"""
|
|
36
|
-
|
|
38
|
+
初始化路由管理器
|
|
37
39
|
|
|
38
40
|
{!--< tips >!--}
|
|
39
41
|
会自动创建FastAPI实例并设置核心路由
|
|
40
42
|
{!--< /tips >!--}
|
|
41
43
|
"""
|
|
42
44
|
self.app = FastAPI(
|
|
43
|
-
title="ErisPulse
|
|
44
|
-
description="
|
|
45
|
+
title="ErisPulse Router",
|
|
46
|
+
description="统一路由管理入口点",
|
|
45
47
|
version="1.0.0"
|
|
46
48
|
)
|
|
47
|
-
self.
|
|
49
|
+
self._http_routes: Dict[str, Dict[str, Callable]] = defaultdict(dict)
|
|
48
50
|
self._websocket_routes: Dict[str, Dict[str, Tuple[Callable, Optional[Callable]]]] = defaultdict(dict)
|
|
49
51
|
self.base_url = ""
|
|
50
52
|
self._server_task: Optional[asyncio.Task] = None
|
|
@@ -66,7 +68,7 @@ class AdapterServer:
|
|
|
66
68
|
:return:
|
|
67
69
|
Dict[str, str]: 包含服务状态的字典
|
|
68
70
|
"""
|
|
69
|
-
return {"status": "ok", "service": "ErisPulse
|
|
71
|
+
return {"status": "ok", "service": "ErisPulse Router"}
|
|
70
72
|
|
|
71
73
|
@self.app.get("/routes")
|
|
72
74
|
async def list_routes() -> Dict[str, Any]:
|
|
@@ -74,36 +76,23 @@ class AdapterServer:
|
|
|
74
76
|
列出所有已注册路由
|
|
75
77
|
|
|
76
78
|
:return:
|
|
77
|
-
Dict[str, Any]:
|
|
78
|
-
{
|
|
79
|
-
"http_routes": [
|
|
80
|
-
{
|
|
81
|
-
"path": "/adapter1/route1",
|
|
82
|
-
"adapter": "adapter1",
|
|
83
|
-
"methods": ["POST"]
|
|
84
|
-
},
|
|
85
|
-
...
|
|
86
|
-
],
|
|
87
|
-
"websocket_routes": [
|
|
88
|
-
{
|
|
89
|
-
"path": "/adapter1/ws",
|
|
90
|
-
"adapter": "adapter1",
|
|
91
|
-
"requires_auth": true
|
|
92
|
-
},
|
|
93
|
-
...
|
|
94
|
-
],
|
|
95
|
-
"base_url": self.base_url
|
|
96
|
-
}
|
|
79
|
+
Dict[str, Any]: 包含所有路由信息的字典
|
|
97
80
|
"""
|
|
98
81
|
http_routes = []
|
|
99
|
-
for adapter, routes in self.
|
|
82
|
+
for adapter, routes in self._http_routes.items():
|
|
100
83
|
for path, handler in routes.items():
|
|
101
|
-
|
|
102
|
-
|
|
84
|
+
# 查找对应的路由对象
|
|
85
|
+
route_obj = None
|
|
86
|
+
for route in self.app.router.routes:
|
|
87
|
+
if isinstance(route, APIRoute) and route.path == path:
|
|
88
|
+
route_obj = route
|
|
89
|
+
break
|
|
90
|
+
|
|
91
|
+
if route_obj:
|
|
103
92
|
http_routes.append({
|
|
104
93
|
"path": path,
|
|
105
94
|
"adapter": adapter,
|
|
106
|
-
"methods":
|
|
95
|
+
"methods": list(route_obj.methods)
|
|
107
96
|
})
|
|
108
97
|
|
|
109
98
|
websocket_routes = []
|
|
@@ -121,9 +110,9 @@ class AdapterServer:
|
|
|
121
110
|
"base_url": self.base_url
|
|
122
111
|
}
|
|
123
112
|
|
|
124
|
-
def
|
|
113
|
+
def register_http_route(
|
|
125
114
|
self,
|
|
126
|
-
|
|
115
|
+
module_name: str,
|
|
127
116
|
path: str,
|
|
128
117
|
handler: Callable,
|
|
129
118
|
methods: List[str] = ["POST"]
|
|
@@ -131,35 +120,37 @@ class AdapterServer:
|
|
|
131
120
|
"""
|
|
132
121
|
注册HTTP路由
|
|
133
122
|
|
|
134
|
-
:param
|
|
135
|
-
:param path: str 路由路径
|
|
123
|
+
:param module_name: str 模块名称
|
|
124
|
+
:param path: str 路由路径
|
|
136
125
|
:param handler: Callable 处理函数
|
|
137
126
|
:param methods: List[str] HTTP方法列表(默认["POST"])
|
|
138
127
|
|
|
139
128
|
:raises ValueError: 当路径已注册时抛出
|
|
140
|
-
|
|
141
|
-
{!--< tips >!--}
|
|
142
|
-
路径会自动添加适配器前缀,如:/adapter_name/path
|
|
143
|
-
{!--< /tips >!--}
|
|
144
129
|
"""
|
|
145
|
-
full_path = f"/{
|
|
130
|
+
full_path = f"/{module_name}{path}"
|
|
146
131
|
|
|
147
|
-
if full_path in self.
|
|
132
|
+
if full_path in self._http_routes[module_name]:
|
|
148
133
|
raise ValueError(f"路径 {full_path} 已注册")
|
|
149
134
|
|
|
150
135
|
route = APIRoute(
|
|
151
136
|
path=full_path,
|
|
152
137
|
endpoint=handler,
|
|
153
138
|
methods=methods,
|
|
154
|
-
name=f"{
|
|
139
|
+
name=f"{module_name}_{path.replace('/', '_')}"
|
|
155
140
|
)
|
|
156
141
|
self.app.router.routes.append(route)
|
|
157
|
-
self.
|
|
142
|
+
self._http_routes[module_name][full_path] = handler
|
|
158
143
|
logger.info(f"注册HTTP路由: {self.base_url}{full_path} 方法: {methods}")
|
|
159
144
|
|
|
145
|
+
def register_webhook(self, *args, **kwargs) -> None:
|
|
146
|
+
"""
|
|
147
|
+
兼容性方法:注册HTTP路由(适配器旧接口)
|
|
148
|
+
"""
|
|
149
|
+
return self.register_http_route(*args, **kwargs)
|
|
150
|
+
|
|
160
151
|
def register_websocket(
|
|
161
152
|
self,
|
|
162
|
-
|
|
153
|
+
module_name: str,
|
|
163
154
|
path: str,
|
|
164
155
|
handler: Callable[[WebSocket], Awaitable[Any]],
|
|
165
156
|
auth_handler: Optional[Callable[[WebSocket], Awaitable[bool]]] = None,
|
|
@@ -167,29 +158,21 @@ class AdapterServer:
|
|
|
167
158
|
"""
|
|
168
159
|
注册WebSocket路由
|
|
169
160
|
|
|
170
|
-
:param
|
|
171
|
-
:param path: str WebSocket路径
|
|
161
|
+
:param module_name: str 模块名称
|
|
162
|
+
:param path: str WebSocket路径
|
|
172
163
|
:param handler: Callable[[WebSocket], Awaitable[Any]] 主处理函数
|
|
173
164
|
:param auth_handler: Optional[Callable[[WebSocket], Awaitable[bool]]] 认证函数
|
|
174
165
|
|
|
175
166
|
:raises ValueError: 当路径已注册时抛出
|
|
176
|
-
|
|
177
|
-
{!--< tips >!--}
|
|
178
|
-
认证函数应返回布尔值,False将拒绝连接
|
|
179
|
-
{!--< /tips >!--}
|
|
180
167
|
"""
|
|
181
|
-
full_path = f"/{
|
|
168
|
+
full_path = f"/{module_name}{path}"
|
|
182
169
|
|
|
183
|
-
if full_path in self._websocket_routes[
|
|
170
|
+
if full_path in self._websocket_routes[module_name]:
|
|
184
171
|
raise ValueError(f"WebSocket路径 {full_path} 已注册")
|
|
185
172
|
|
|
186
173
|
async def websocket_endpoint(websocket: WebSocket) -> None:
|
|
187
174
|
"""
|
|
188
175
|
WebSocket端点包装器
|
|
189
|
-
|
|
190
|
-
{!--< internal-use >!--}
|
|
191
|
-
处理连接生命周期和错误处理
|
|
192
|
-
{!--< /internal-use >!--}
|
|
193
176
|
"""
|
|
194
177
|
await websocket.accept()
|
|
195
178
|
|
|
@@ -209,17 +192,16 @@ class AdapterServer:
|
|
|
209
192
|
self.app.add_api_websocket_route(
|
|
210
193
|
path=full_path,
|
|
211
194
|
endpoint=websocket_endpoint,
|
|
212
|
-
name=f"{
|
|
195
|
+
name=f"{module_name}_{path.replace('/', '_')}"
|
|
213
196
|
)
|
|
214
|
-
self._websocket_routes[
|
|
197
|
+
self._websocket_routes[module_name][full_path] = (handler, auth_handler)
|
|
215
198
|
logger.info(f"注册WebSocket: {self.base_url}{full_path} {'(需认证)' if auth_handler else ''}")
|
|
216
199
|
|
|
217
200
|
def get_app(self) -> FastAPI:
|
|
218
201
|
"""
|
|
219
202
|
获取FastAPI应用实例
|
|
220
203
|
|
|
221
|
-
:return:
|
|
222
|
-
FastAPI: FastAPI应用实例
|
|
204
|
+
:return: FastAPI应用实例
|
|
223
205
|
"""
|
|
224
206
|
return self.app
|
|
225
207
|
|
|
@@ -231,7 +213,7 @@ class AdapterServer:
|
|
|
231
213
|
ssl_keyfile: Optional[str] = None
|
|
232
214
|
) -> None:
|
|
233
215
|
"""
|
|
234
|
-
|
|
216
|
+
启动路由服务器
|
|
235
217
|
|
|
236
218
|
:param host: str 监听地址(默认"0.0.0.0")
|
|
237
219
|
:param port: int 监听端口(默认8000)
|
|
@@ -252,25 +234,24 @@ class AdapterServer:
|
|
|
252
234
|
config.keyfile = ssl_keyfile
|
|
253
235
|
|
|
254
236
|
self.base_url = f"http{'s' if ssl_certfile else ''}://{host}:{port}"
|
|
255
|
-
logger.info(f"
|
|
237
|
+
logger.info(f"启动路由服务器 {self.base_url}")
|
|
256
238
|
|
|
257
239
|
self._server_task = asyncio.create_task(serve(self.app, config))
|
|
258
240
|
|
|
259
241
|
async def stop(self) -> None:
|
|
260
242
|
"""
|
|
261
243
|
停止服务器
|
|
262
|
-
|
|
263
|
-
{!--< tips >!--}
|
|
264
|
-
会等待所有连接正常关闭
|
|
265
|
-
{!--< /tips >!--}
|
|
266
244
|
"""
|
|
267
245
|
if self._server_task:
|
|
268
246
|
self._server_task.cancel()
|
|
269
247
|
try:
|
|
270
248
|
await self._server_task
|
|
271
249
|
except asyncio.CancelledError:
|
|
272
|
-
logger.info("
|
|
250
|
+
logger.info("路由服务器已停止")
|
|
273
251
|
self._server_task = None
|
|
274
252
|
|
|
253
|
+
# 主要实例
|
|
254
|
+
router = RouterManager()
|
|
275
255
|
|
|
276
|
-
|
|
256
|
+
# 兼容性实例
|
|
257
|
+
adapter_server = router
|
ErisPulse/__init__.py
CHANGED
|
@@ -10,6 +10,9 @@ ErisPulse SDK 主模块
|
|
|
10
10
|
{!--< /tips >!--}
|
|
11
11
|
"""
|
|
12
12
|
|
|
13
|
+
__version__ = "2.1.14dev1"
|
|
14
|
+
__author__ = "ErisPulse"
|
|
15
|
+
|
|
13
16
|
import os
|
|
14
17
|
import sys
|
|
15
18
|
import importlib
|
|
@@ -19,28 +22,36 @@ from typing import Dict, List, Tuple, Type, Any
|
|
|
19
22
|
from pathlib import Path
|
|
20
23
|
|
|
21
24
|
# BaseModules: SDK核心模块
|
|
22
|
-
from .Core import util
|
|
23
|
-
from .Core import raiserr
|
|
24
25
|
from .Core import logger
|
|
25
26
|
from .Core import env
|
|
26
27
|
from .Core import mods
|
|
27
28
|
from .Core import adapter, AdapterFather, SendDSL
|
|
28
|
-
from .Core import adapter_server
|
|
29
|
+
from .Core import router, adapter_server
|
|
30
|
+
from .Core import exceptions
|
|
31
|
+
from .Core import config
|
|
29
32
|
|
|
30
33
|
sdk = sys.modules[__name__]
|
|
31
34
|
|
|
32
35
|
BaseModules = {
|
|
33
|
-
"util": util,
|
|
34
36
|
"logger": logger,
|
|
35
|
-
"
|
|
37
|
+
"config": config,
|
|
38
|
+
"exceptions": exceptions,
|
|
36
39
|
"env": env,
|
|
37
40
|
"mods": mods,
|
|
38
41
|
"adapter": adapter,
|
|
42
|
+
"router": router,
|
|
43
|
+
"adapter_server": adapter_server,
|
|
39
44
|
"SendDSL": SendDSL,
|
|
40
45
|
"AdapterFather": AdapterFather,
|
|
41
46
|
"BaseAdapter": AdapterFather
|
|
42
47
|
}
|
|
43
48
|
|
|
49
|
+
import asyncio
|
|
50
|
+
|
|
51
|
+
asyncio_loop = asyncio.get_event_loop()
|
|
52
|
+
|
|
53
|
+
exceptions.setup_async_loop(asyncio_loop)
|
|
54
|
+
|
|
44
55
|
for module, moduleObj in BaseModules.items():
|
|
45
56
|
setattr(sdk, module, moduleObj)
|
|
46
57
|
|
|
@@ -664,23 +675,24 @@ def _prepare_environment() -> bool:
|
|
|
664
675
|
{!--< internal-use >!--}
|
|
665
676
|
准备运行环境
|
|
666
677
|
|
|
667
|
-
|
|
668
|
-
2. 加载环境变量配置
|
|
678
|
+
初始化项目环境文件
|
|
669
679
|
|
|
670
680
|
:return: bool 环境准备是否成功
|
|
671
681
|
"""
|
|
672
682
|
logger.info("[Init] 准备初始化环境...")
|
|
673
683
|
try:
|
|
684
|
+
from .Core.erispulse_config import get_erispulse_config
|
|
685
|
+
get_erispulse_config()
|
|
686
|
+
logger.info("[Init] 配置文件已加载")
|
|
687
|
+
|
|
674
688
|
main_init = init_progress()
|
|
675
689
|
if main_init:
|
|
676
690
|
logger.info("[Init] 项目入口已生成, 你可以在 main.py 中编写一些代码")
|
|
677
|
-
env.load_env_file()
|
|
678
691
|
return True
|
|
679
692
|
except Exception as e:
|
|
680
693
|
logger.error(f"环境准备失败: {e}")
|
|
681
694
|
return False
|
|
682
695
|
|
|
683
|
-
|
|
684
696
|
def init() -> bool:
|
|
685
697
|
"""
|
|
686
698
|
SDK初始化入口
|
ErisPulse/__main__.py
CHANGED
|
@@ -19,7 +19,6 @@ import json
|
|
|
19
19
|
import asyncio
|
|
20
20
|
from urllib.parse import urlparse
|
|
21
21
|
from typing import List, Dict, Tuple, Optional, Callable, Any
|
|
22
|
-
from importlib.metadata import version, PackageNotFoundError
|
|
23
22
|
from watchdog.observers import Observer
|
|
24
23
|
from watchdog.events import FileSystemEventHandler
|
|
25
24
|
|
|
@@ -188,26 +187,38 @@ class PackageManager:
|
|
|
188
187
|
|
|
189
188
|
try:
|
|
190
189
|
# 查找模块和适配器
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
190
|
+
entry_points = importlib.metadata.entry_points()
|
|
191
|
+
|
|
192
|
+
# 处理模块
|
|
193
|
+
if hasattr(entry_points, 'select'):
|
|
194
|
+
module_entries = entry_points.select(group='erispulse.module')
|
|
195
|
+
else:
|
|
196
|
+
module_entries = entry_points.get('erispulse.module', [])
|
|
197
|
+
|
|
198
|
+
for entry in module_entries:
|
|
199
|
+
dist = entry.dist
|
|
200
|
+
packages["modules"][entry.name] = {
|
|
201
|
+
"package": dist.metadata["Name"],
|
|
202
|
+
"version": dist.version,
|
|
203
|
+
"summary": dist.metadata["Summary"],
|
|
204
|
+
"enabled": self._is_module_enabled(entry.name)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
# 处理适配器
|
|
208
|
+
if hasattr(entry_points, 'select'):
|
|
209
|
+
adapter_entries = entry_points.select(group='erispulse.adapter')
|
|
210
|
+
else:
|
|
211
|
+
adapter_entries = entry_points.get('erispulse.adapter', [])
|
|
212
|
+
|
|
213
|
+
for entry in adapter_entries:
|
|
214
|
+
dist = entry.dist
|
|
215
|
+
packages["adapters"][entry.name] = {
|
|
216
|
+
"package": dist.metadata["Name"],
|
|
217
|
+
"version": dist.version,
|
|
218
|
+
"summary": dist.metadata["Summary"]
|
|
219
|
+
}
|
|
208
220
|
|
|
209
221
|
# 查找CLI扩展
|
|
210
|
-
entry_points = importlib.metadata.entry_points()
|
|
211
222
|
if hasattr(entry_points, 'select'):
|
|
212
223
|
cli_entries = entry_points.select(group='erispulse.cli')
|
|
213
224
|
else:
|
|
@@ -222,9 +233,9 @@ class PackageManager:
|
|
|
222
233
|
}
|
|
223
234
|
|
|
224
235
|
except Exception as e:
|
|
225
|
-
|
|
236
|
+
print(f"[error] 获取已安装包信息失败: {e}")
|
|
226
237
|
import traceback
|
|
227
|
-
|
|
238
|
+
print(traceback.format_exc())
|
|
228
239
|
|
|
229
240
|
return packages
|
|
230
241
|
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
ErisPulse/__init__.py,sha256=YoqCrqbR1dxjajBii6D4iebuVUl2bZaZYbpPXEgGBz8,26428
|
|
2
|
+
ErisPulse/__main__.py,sha256=aDYN5_11PdL3tj2ruhNoXwNc9TmAUnBtFujQgnEf_sI,37573
|
|
3
|
+
ErisPulse/Core/__init__.py,sha256=hX2yEt9VSD3JubiofoQdcY4v1lnQUU02dhuVADkMTVo,437
|
|
4
|
+
ErisPulse/Core/adapter.py,sha256=oBJOp6SS8sm8NgIxQwetGsHu24wHNXz7ESQ5yKJSo7Q,18234
|
|
5
|
+
ErisPulse/Core/config.py,sha256=2BRWINOqKtHSCP4KfhuiRpGwR96jWGKV7gjZSi_VQHE,2397
|
|
6
|
+
ErisPulse/Core/env.py,sha256=U45f9WtriVyd3tW1N8to-ZvpzcF9gD8DJzNTC1jY2cM,17665
|
|
7
|
+
ErisPulse/Core/erispulse_config.py,sha256=QDx401hNX9JcSHqCSVK33X6VTubl6HI1znAK3T_J0K0,3034
|
|
8
|
+
ErisPulse/Core/exceptions.py,sha256=zuTREGczwGzbYT4Z6dACqHwgNRpiJeLFR8aCxFdOg7k,3667
|
|
9
|
+
ErisPulse/Core/logger.py,sha256=8hdbF6x3JpsQbbeEjvbSej134q5oV0wafagpWq3Nbeg,11223
|
|
10
|
+
ErisPulse/Core/mods.py,sha256=2yIq8t9Ca9CBPRiZU0yr8Lc0XGmmkB7LlH-5FWqXjw4,7023
|
|
11
|
+
ErisPulse/Core/router.py,sha256=66hT8VC2dVNX-dANldoOPDcqQ94hidFkNnvKgAPemGQ,8491
|
|
12
|
+
erispulse-2.1.14a1.dist-info/METADATA,sha256=qm46_dLloUuS0n5tMXxL2YTSdyleOTjxzT1TQyj1VQ4,6261
|
|
13
|
+
erispulse-2.1.14a1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
14
|
+
erispulse-2.1.14a1.dist-info/entry_points.txt,sha256=Jss71M6nEha0TA-DyVZugPYdcL14s9QpiOeIlgWxzOc,182
|
|
15
|
+
erispulse-2.1.14a1.dist-info/licenses/LICENSE,sha256=4jyqikiB0G0n06CEEMMTzTXjE4IShghSlB74skMSPQs,1464
|
|
16
|
+
erispulse-2.1.14a1.dist-info/RECORD,,
|
ErisPulse/Core/raiserr.py
DELETED
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
ErisPulse 错误管理系统
|
|
3
|
-
|
|
4
|
-
提供全局异常捕获功能。不再推荐使用自定义错误注册功能。
|
|
5
|
-
|
|
6
|
-
{!--< tips >!--}
|
|
7
|
-
1. 请使用Python原生异常抛出方法
|
|
8
|
-
2. 系统会自动捕获并格式化所有未处理异常
|
|
9
|
-
3. 注册功能已标记为弃用,将在未来版本移除
|
|
10
|
-
{!--< /tips >!--}
|
|
11
|
-
"""
|
|
12
|
-
|
|
13
|
-
import sys
|
|
14
|
-
import traceback
|
|
15
|
-
import asyncio
|
|
16
|
-
from typing import Dict, Any, Optional, Type, Callable, List, Set, Tuple, Union
|
|
17
|
-
|
|
18
|
-
class Error:
|
|
19
|
-
"""
|
|
20
|
-
错误管理器
|
|
21
|
-
|
|
22
|
-
{!--< deprecated >!--} 请使用Python原生异常抛出方法 | 2025-07-18
|
|
23
|
-
|
|
24
|
-
{!--< tips >!--}
|
|
25
|
-
1. 注册功能将在未来版本移除
|
|
26
|
-
2. 请直接使用raise Exception("message")方式抛出异常
|
|
27
|
-
{!--< /tips >!--}
|
|
28
|
-
"""
|
|
29
|
-
|
|
30
|
-
def __init__(self):
|
|
31
|
-
self._types = {}
|
|
32
|
-
|
|
33
|
-
def register(self, name: str, doc: str = "", base: Type[Exception] = Exception) -> Type[Exception]:
|
|
34
|
-
"""
|
|
35
|
-
注册新的错误类型
|
|
36
|
-
|
|
37
|
-
{!--< deprecated >!--} 请使用Python原生异常抛出方法 | 2025-07-18
|
|
38
|
-
|
|
39
|
-
:param name: 错误类型名称
|
|
40
|
-
:param doc: 错误描述文档
|
|
41
|
-
:param base: 基础异常类
|
|
42
|
-
:return: 注册的错误类
|
|
43
|
-
"""
|
|
44
|
-
if name not in self._types:
|
|
45
|
-
err_cls = type(name, (base,), {"__doc__": doc})
|
|
46
|
-
self._types[name] = err_cls
|
|
47
|
-
return self._types[name]
|
|
48
|
-
|
|
49
|
-
def __getattr__(self, name: str) -> Callable[..., None]:
|
|
50
|
-
"""
|
|
51
|
-
动态获取错误抛出函数
|
|
52
|
-
|
|
53
|
-
{!--< deprecated >!--} 请使用Python原生异常抛出方法 | 2025-07-18
|
|
54
|
-
|
|
55
|
-
:param name: 错误类型名称
|
|
56
|
-
:return: 错误抛出函数
|
|
57
|
-
|
|
58
|
-
:raises AttributeError: 当错误类型未注册时抛出
|
|
59
|
-
"""
|
|
60
|
-
def raiser(msg: str, exit: bool = False) -> None:
|
|
61
|
-
"""
|
|
62
|
-
错误抛出函数
|
|
63
|
-
|
|
64
|
-
:param msg: 错误消息
|
|
65
|
-
:param exit: 是否退出程序
|
|
66
|
-
"""
|
|
67
|
-
from .logger import logger
|
|
68
|
-
err_cls = self._types.get(name) or self.register(name)
|
|
69
|
-
exc = err_cls(msg)
|
|
70
|
-
|
|
71
|
-
red = '\033[91m'
|
|
72
|
-
reset = '\033[0m'
|
|
73
|
-
|
|
74
|
-
logger.error(f"{red}{name}: {msg} | {err_cls.__doc__}{reset}")
|
|
75
|
-
logger.error(f"{red}{ ''.join(traceback.format_stack()) }{reset}")
|
|
76
|
-
|
|
77
|
-
if exit:
|
|
78
|
-
raise exc
|
|
79
|
-
return raiser
|
|
80
|
-
|
|
81
|
-
def info(self, name: Optional[str] = None) -> Dict[str, Any]:
|
|
82
|
-
"""
|
|
83
|
-
获取错误信息
|
|
84
|
-
|
|
85
|
-
{!--< deprecated >!--} 此功能将在未来版本移除 | 2025-07-18
|
|
86
|
-
|
|
87
|
-
:param name: 错误类型名称(可选)
|
|
88
|
-
:return: 错误信息字典
|
|
89
|
-
"""
|
|
90
|
-
result = {}
|
|
91
|
-
for err_name, err_cls in self._types.items():
|
|
92
|
-
result[err_name] = {
|
|
93
|
-
"type": err_name,
|
|
94
|
-
"doc": getattr(err_cls, "__doc__", ""),
|
|
95
|
-
"class": err_cls,
|
|
96
|
-
}
|
|
97
|
-
if name is None:
|
|
98
|
-
return result
|
|
99
|
-
err_cls = self._types.get(name)
|
|
100
|
-
if not err_cls:
|
|
101
|
-
return {
|
|
102
|
-
"type": None,
|
|
103
|
-
"doc": None,
|
|
104
|
-
"class": None,
|
|
105
|
-
}
|
|
106
|
-
return {
|
|
107
|
-
"type": name,
|
|
108
|
-
"doc": getattr(err_cls, "__doc__", ""),
|
|
109
|
-
"class": err_cls,
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
raiserr = Error()
|
|
114
|
-
|
|
115
|
-
def global_exception_handler(exc_type: Type[Exception], exc_value: Exception, exc_traceback: Any) -> None:
|
|
116
|
-
"""
|
|
117
|
-
全局异常处理器
|
|
118
|
-
|
|
119
|
-
:param exc_type: 异常类型
|
|
120
|
-
:param exc_value: 异常值
|
|
121
|
-
:param exc_traceback: 追踪信息
|
|
122
|
-
"""
|
|
123
|
-
RED = '\033[91m'
|
|
124
|
-
YELLOW = '\033[93m'
|
|
125
|
-
BLUE = '\033[94m'
|
|
126
|
-
RESET = '\033[0m'
|
|
127
|
-
|
|
128
|
-
error_title = f"{RED}{exc_type.__name__}{RESET}: {YELLOW}{exc_value}{RESET}"
|
|
129
|
-
traceback_lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
|
|
130
|
-
|
|
131
|
-
colored_traceback = []
|
|
132
|
-
for line in traceback_lines:
|
|
133
|
-
if "File " in line and ", line " in line:
|
|
134
|
-
parts = line.split(', line ')
|
|
135
|
-
colored_line = f"{BLUE}{parts[0]}{RESET}, line {parts[1]}"
|
|
136
|
-
colored_traceback.append(colored_line)
|
|
137
|
-
else:
|
|
138
|
-
colored_traceback.append(f"{RED}{line}{RESET}")
|
|
139
|
-
|
|
140
|
-
full_error = f"""
|
|
141
|
-
{error_title}
|
|
142
|
-
{RED}Traceback:{RESET}
|
|
143
|
-
{colored_traceback}"""
|
|
144
|
-
|
|
145
|
-
sys.stderr.write(full_error)
|
|
146
|
-
|
|
147
|
-
def async_exception_handler(loop: asyncio.AbstractEventLoop, context: Dict[str, Any]) -> None:
|
|
148
|
-
"""
|
|
149
|
-
异步异常处理器
|
|
150
|
-
|
|
151
|
-
:param loop: 事件循环
|
|
152
|
-
:param context: 上下文字典
|
|
153
|
-
"""
|
|
154
|
-
RED = '\033[91m'
|
|
155
|
-
YELLOW = '\033[93m'
|
|
156
|
-
BLUE = '\033[94m'
|
|
157
|
-
RESET = '\033[0m'
|
|
158
|
-
|
|
159
|
-
exception = context.get('exception')
|
|
160
|
-
if exception:
|
|
161
|
-
tb = ''.join(traceback.format_exception(type(exception), exception, exception.__traceback__))
|
|
162
|
-
|
|
163
|
-
colored_tb = []
|
|
164
|
-
for line in tb.split('\n'):
|
|
165
|
-
if "File " in line and ", line " in line:
|
|
166
|
-
parts = line.split(', line ')
|
|
167
|
-
colored_line = f"{BLUE}{parts[0]}{RESET}, line {parts[1]}"
|
|
168
|
-
colored_tb.append(colored_line)
|
|
169
|
-
else:
|
|
170
|
-
colored_tb.append(f"{RED}{line}{RESET}")
|
|
171
|
-
|
|
172
|
-
error_msg = f"""{RED}{type(exception).__name__}{RESET}: {YELLOW}{exception}{RESET}
|
|
173
|
-
{RED}Traceback:{RESET}
|
|
174
|
-
{colored_tb}"""
|
|
175
|
-
sys.stderr.write(error_msg)
|
|
176
|
-
else:
|
|
177
|
-
msg = context.get('message', 'Unknown async error')
|
|
178
|
-
sys.stderr.write(f"{RED}Async Error{RESET}: {YELLOW}{msg}{RESET}")
|
|
179
|
-
|
|
180
|
-
sys.excepthook = global_exception_handler
|
|
181
|
-
asyncio.get_event_loop().set_exception_handler(async_exception_handler)
|