pytest-api-framework-alpha 1.0.5__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.
- framework/__init__.py +1 -0
- framework/assertion/__init__.py +3 -0
- framework/assertion/retry_assert.py +67 -0
- framework/assertion/webhook_assert.py +129 -0
- framework/client/__init__.py +3 -0
- framework/client/crrm_client.py +155 -0
- framework/client/http_client.py +340 -0
- framework/client/mq_client.py +178 -0
- framework/client/websocket_client.py +414 -0
- framework/conftest.py +526 -0
- framework/core/__init__.py +3 -0
- framework/core/base_class.py +871 -0
- framework/core/extract.py +185 -0
- framework/core/global_attribute.py +187 -0
- framework/core/hooks/__init__.py +3 -0
- framework/core/hooks/filters.py +217 -0
- framework/core/hooks/reporter.py +228 -0
- framework/core/hooks/session.py +345 -0
- framework/core/hooks/sorting.py +84 -0
- framework/core/models.py +82 -0
- framework/core/render_data.py +309 -0
- framework/core/validate.py +648 -0
- framework/db/__init__.py +3 -0
- framework/db/mysql_db.py +226 -0
- framework/db/redis_db.py +319 -0
- framework/exceptions.py +22 -0
- framework/exit_code.py +20 -0
- framework/gen/__init__.py +3 -0
- framework/gen/case_gen.py +1268 -0
- framework/gen/create_app.py +265 -0
- framework/report.py +111 -0
- framework/script.py +35 -0
- framework/settings.py +93 -0
- framework/utils/__init__.py +3 -0
- framework/utils/cognito_util.py +348 -0
- framework/utils/common.py +298 -0
- framework/utils/date_util.py +218 -0
- framework/utils/encrypt.py +448 -0
- framework/utils/lark_util.py +167 -0
- framework/utils/log_util.py +10 -0
- framework/utils/mock_util.py +236 -0
- framework/utils/yaml_util.py +169 -0
- framework/ws_server.py +167 -0
- pytest_api_framework_alpha-1.0.5.dist-info/METADATA +98 -0
- pytest_api_framework_alpha-1.0.5.dist-info/RECORD +48 -0
- pytest_api_framework_alpha-1.0.5.dist-info/WHEEL +5 -0
- pytest_api_framework_alpha-1.0.5.dist-info/licenses/LICENSE +21 -0
- pytest_api_framework_alpha-1.0.5.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""
|
|
2
|
+
HTTP 客户端模块,封装了 requests 库,提供 HTTP 请求发送、响应封装、断言校验和变量提取等功能。
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any, List, Callable
|
|
7
|
+
import urllib.parse
|
|
8
|
+
from urllib.parse import urljoin
|
|
9
|
+
|
|
10
|
+
import allure
|
|
11
|
+
import requests
|
|
12
|
+
import simplejson as built_json
|
|
13
|
+
|
|
14
|
+
from box import Box, BoxList
|
|
15
|
+
from jsonpath import jsonpath as jp
|
|
16
|
+
from requests.models import Response
|
|
17
|
+
from requests_toolbelt import MultipartEncoder
|
|
18
|
+
|
|
19
|
+
from framework.core.extract import Extract
|
|
20
|
+
from framework.core.validate import Validate
|
|
21
|
+
from framework.utils.log_util import logger
|
|
22
|
+
from framework.core.global_attribute import CONTEXT
|
|
23
|
+
from framework.settings import CONSOLE_DETAILED_LOG
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ResponseUtil(object):
|
|
27
|
+
"""HTTP 响应工具类,封装响应对象的解析、断言和变量提取。"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, response: Response, app: str | None = None) -> None:
|
|
30
|
+
"""
|
|
31
|
+
初始化响应工具类。
|
|
32
|
+
@param response: requests 响应对象
|
|
33
|
+
@param app: 所属应用实例
|
|
34
|
+
"""
|
|
35
|
+
self.app = app
|
|
36
|
+
self.response = response
|
|
37
|
+
self._json = None
|
|
38
|
+
|
|
39
|
+
if not response.content:
|
|
40
|
+
self.box = response.text
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
content_type = response.headers.get("Content-Type", "").lower()
|
|
44
|
+
# JSON 类型:解析 JSON 响应,根据数据类型封装为 Box 或 BoxList
|
|
45
|
+
if "application/json" in content_type:
|
|
46
|
+
data = self.response.json()
|
|
47
|
+
self._json = data
|
|
48
|
+
if isinstance(data, dict):
|
|
49
|
+
self.box = Box(data)
|
|
50
|
+
elif isinstance(data, list):
|
|
51
|
+
self.box = BoxList(data)
|
|
52
|
+
else:
|
|
53
|
+
self.box = data
|
|
54
|
+
|
|
55
|
+
# URL 编码表单类型:将查询字符串解析为字典
|
|
56
|
+
elif "application/x-www-form-urlencoded" in content_type:
|
|
57
|
+
parsed = urllib.parse.parse_qs(self.response.text)
|
|
58
|
+
# parse_qs 返回 {key: [value]},可以转成 dict
|
|
59
|
+
parsed = {k: v[0] if len(v) == 1 else v for k, v in parsed.items()}
|
|
60
|
+
self.box = Box(parsed)
|
|
61
|
+
|
|
62
|
+
# multipart 类型:文件上传场景,直接返回原始字节内容
|
|
63
|
+
elif "multipart/form-data" in content_type:
|
|
64
|
+
self.box = self.response.content
|
|
65
|
+
|
|
66
|
+
# 其他类型(如文件下载):直接返回原始字节内容
|
|
67
|
+
else:
|
|
68
|
+
self.box = self.response.content
|
|
69
|
+
|
|
70
|
+
except Exception as e:
|
|
71
|
+
self.box = response.text
|
|
72
|
+
|
|
73
|
+
def __getattr__(self, name: str) -> Any:
|
|
74
|
+
"""获取属性,优先从 box 对象获取,若不存在则从原始 response 获取。"""
|
|
75
|
+
try:
|
|
76
|
+
return getattr(self.box, name)
|
|
77
|
+
except AttributeError:
|
|
78
|
+
return getattr(self.response, name)
|
|
79
|
+
|
|
80
|
+
def __str__(self) -> str:
|
|
81
|
+
"""返回响应文本内容。"""
|
|
82
|
+
return self.text
|
|
83
|
+
|
|
84
|
+
def jsonpath(self, expr: str, headers: bool = False) -> Any:
|
|
85
|
+
"""
|
|
86
|
+
使用 jsonpath 语法从响应体或响应头中提取内容。
|
|
87
|
+
@param expr: jsonpath 表达式
|
|
88
|
+
@param headers: 若为 True,则从响应头中提取,否则从响应体中提取
|
|
89
|
+
@return: 匹配结果;若匹配到单个值则直接返回,否则返回列表;无匹配时返回空字符串
|
|
90
|
+
"""
|
|
91
|
+
result = jp(dict(self.response.headers), expr) if headers else jp(self.json(), expr)
|
|
92
|
+
if result is False: # jsonpath 无匹配时返回 False
|
|
93
|
+
return ""
|
|
94
|
+
if len(result) == 1: # 匹配到唯一值时直接返回
|
|
95
|
+
return result[0]
|
|
96
|
+
return result
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def jsonp(self) -> Any:
|
|
100
|
+
"""解析 JSONP 格式的响应,返回 JSON 数据。"""
|
|
101
|
+
jsonp_re = re.compile(r".*?\((?P<text>.*)\)") # 匹配 JSONP 格式:func(data)
|
|
102
|
+
return built_json.loads(jsonp_re.match(self.response.text).group("text"))
|
|
103
|
+
|
|
104
|
+
def json(self) -> Any:
|
|
105
|
+
"""获取 JSON 格式的响应数据(带缓存,避免重复解析)。"""
|
|
106
|
+
if self._json is None:
|
|
107
|
+
self._json = self.response.json() # 缓存 JSON 数据
|
|
108
|
+
return self._json
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
def text(self) -> str:
|
|
112
|
+
"""获取响应文本内容。"""
|
|
113
|
+
return self.response.text
|
|
114
|
+
|
|
115
|
+
def extract(self, key: str, expression: str) -> None:
|
|
116
|
+
"""
|
|
117
|
+
从响应中提取变量并存储。
|
|
118
|
+
@param key: 变量保存的名称
|
|
119
|
+
@param expression: 变量提取表达式
|
|
120
|
+
"""
|
|
121
|
+
Extract(self.response, self.app).extract(key, expression)
|
|
122
|
+
|
|
123
|
+
def extracts(self, expressions: List[dict]) -> None:
|
|
124
|
+
"""
|
|
125
|
+
批量从响应中提取变量并存储。
|
|
126
|
+
@param expressions: 变量提取表达式列表
|
|
127
|
+
"""
|
|
128
|
+
Extract(self.response, self.app).extracts(expressions)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class HttpClient(object):
|
|
132
|
+
"""HTTP 客户端,封装了常见的 HTTP 请求方法(GET/POST/PUT/DELETE/PATCH/HEAD/OPTIONS),
|
|
133
|
+
支持请求头管理、响应处理、断言和变量提取。
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
def __init__(self, headers: dict[str, str] | None = None) -> None:
|
|
137
|
+
"""
|
|
138
|
+
初始化 HTTP 客户端。
|
|
139
|
+
@param headers: 默认请求头
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
self.headers = {
|
|
143
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
|
|
144
|
+
"Content-Type": "application/json"
|
|
145
|
+
}
|
|
146
|
+
self.headers.update(headers or {})
|
|
147
|
+
# 登录响应里的 token 有效期(秒)。Login 实现拿到 expires_in 后写在这里,
|
|
148
|
+
# 框架据此算下次重新登录的时间点;留空则回落到配置里的 token_expiry
|
|
149
|
+
self.expires_in = None
|
|
150
|
+
|
|
151
|
+
def __send_request(self, data: Any) -> ResponseUtil:
|
|
152
|
+
"""发送 HTTP 请求,记录请求/响应日志,执行断言和变量提取。
|
|
153
|
+
@param data: 请求数据,包含 request 配置、validate 断言规则、extract 提取规则等
|
|
154
|
+
@return: ResponseUtil 实例
|
|
155
|
+
"""
|
|
156
|
+
_is_multipart = data.get("_is_multipart") # 是否为 multipart 上传请求
|
|
157
|
+
request_obj = data.get("request") # 请求参数配置
|
|
158
|
+
with allure.step("发送请求"):
|
|
159
|
+
request_obj["headers"].update(self.headers) # 合并默认请求头
|
|
160
|
+
if _is_multipart:
|
|
161
|
+
m = MultipartEncoder(fields=request_obj["data"]) # 构建 multipart 编码器
|
|
162
|
+
request_obj["data"] = m
|
|
163
|
+
request_obj["headers"]['Content-Type'] = m.content_type # 更新 Content-Type
|
|
164
|
+
response = ResponseUtil(requests.request(**request_obj), data.get("app"))
|
|
165
|
+
|
|
166
|
+
with allure.step(f"请求url: {request_obj.get('url')}"):
|
|
167
|
+
logger.info(f"⮕ url: {request_obj.get('url')}")
|
|
168
|
+
|
|
169
|
+
with allure.step(f"请求method: {request_obj.get('method')}"):
|
|
170
|
+
logger.info(f"⮕ method: {request_obj.get('method')}")
|
|
171
|
+
|
|
172
|
+
with allure.step(f"请求headers: {HttpClient.json(request_obj.get('headers'))}"):
|
|
173
|
+
if CONSOLE_DETAILED_LOG:
|
|
174
|
+
logger.info(f"⮕ headers: {HttpClient.json(request_obj.get('headers'))}")
|
|
175
|
+
|
|
176
|
+
params = request_obj.get('params') # 查询参数
|
|
177
|
+
if params:
|
|
178
|
+
with allure.step(f"请求参数params: {HttpClient.json(params)}"):
|
|
179
|
+
logger.info(f"⮕ params: {HttpClient.json(params)}")
|
|
180
|
+
|
|
181
|
+
req_data = request_obj.get('data') # 请求体(表单格式)
|
|
182
|
+
if req_data:
|
|
183
|
+
with allure.step(f"请求参数data: {req_data}"):
|
|
184
|
+
logger.info(f"⮕ data: {req_data}")
|
|
185
|
+
|
|
186
|
+
req_json = request_obj.get('json') # 请求体(JSON 格式)
|
|
187
|
+
if req_json:
|
|
188
|
+
with allure.step(f"请求参数json: {HttpClient.json(req_json)}"):
|
|
189
|
+
logger.info(f"⮕ json: {HttpClient.json(req_json)}")
|
|
190
|
+
|
|
191
|
+
with allure.step("响应结果"):
|
|
192
|
+
with allure.step(f"响应http code: {response.status_code}"):
|
|
193
|
+
logger.info(f"⬅ http code: {response.status_code}")
|
|
194
|
+
|
|
195
|
+
with allure.step(f"响应headers: {HttpClient.json(dict(response.headers))}"):
|
|
196
|
+
if CONSOLE_DETAILED_LOG:
|
|
197
|
+
logger.info(f"⬅ headers: {HttpClient.json(dict(response.headers))}")
|
|
198
|
+
|
|
199
|
+
try:
|
|
200
|
+
with allure.step(f"响应body: {HttpClient.json(response.json())}"):
|
|
201
|
+
logger.info(f"⬅ body: {HttpClient.json(response.json())}")
|
|
202
|
+
except Exception:
|
|
203
|
+
with allure.step(f"响应body: {response.text}"):
|
|
204
|
+
logger.info(f"⬅ body: {response.text}")
|
|
205
|
+
|
|
206
|
+
# 断言校验:若配置了 validate 规则则执行断言
|
|
207
|
+
validates = data.get("validate")
|
|
208
|
+
if validates:
|
|
209
|
+
with allure.step("结果断言"):
|
|
210
|
+
Validate(data, response).valid(validates)
|
|
211
|
+
|
|
212
|
+
# 变量提取:若配置了 extract 规则则从响应中提取变量
|
|
213
|
+
expressions = data.get("extract")
|
|
214
|
+
app = data.get("app")
|
|
215
|
+
if expressions:
|
|
216
|
+
with allure.step("提取变量"):
|
|
217
|
+
Extract(response, app).extracts(expressions)
|
|
218
|
+
|
|
219
|
+
return response
|
|
220
|
+
|
|
221
|
+
def request(self, data: Any = None, **kwargs: Any) -> ResponseUtil:
|
|
222
|
+
"""执行 HTTP 请求,支持直接传入请求配置或通过关键字参数构建请求。
|
|
223
|
+
@param data: 请求配置字典(包含 request、validate、extract 等字段),不传则按 kwargs 裸发
|
|
224
|
+
@param kwargs: 其他请求参数(如 headers)
|
|
225
|
+
@return: ResponseUtil 实例
|
|
226
|
+
"""
|
|
227
|
+
if data:
|
|
228
|
+
data["request"]["headers"].update(kwargs.pop("headers", {}))
|
|
229
|
+
data["request"].update(kwargs)
|
|
230
|
+
return self.__send_request(data)
|
|
231
|
+
|
|
232
|
+
return ResponseUtil(requests.request(headers=self.headers, **kwargs))
|
|
233
|
+
|
|
234
|
+
def _make_request(self, method: str, app: str | None, url: str, **kwargs: Any) -> ResponseUtil:
|
|
235
|
+
"""构建完整 URL 并发送请求。
|
|
236
|
+
|
|
237
|
+
统一走 request() 的 data 分支,这样快捷方法也能拿到完整的请求/响应日志、
|
|
238
|
+
allure 步骤以及 validate/extract 能力。
|
|
239
|
+
@param method: HTTP 方法(get/post/put/delete/patch/head/options)
|
|
240
|
+
@param app: 应用名称,用于获取 domain 配置;不传则 url 必须是完整地址
|
|
241
|
+
@param url: API 路径
|
|
242
|
+
@param kwargs: 其他请求参数
|
|
243
|
+
@return: ResponseUtil 实例
|
|
244
|
+
"""
|
|
245
|
+
domain = CONTEXT.get(app=app, key="domain") if app else None
|
|
246
|
+
request_obj: dict[str, Any] = {
|
|
247
|
+
"method": method,
|
|
248
|
+
"url": urljoin(domain, url) if domain else url,
|
|
249
|
+
"headers": {},
|
|
250
|
+
}
|
|
251
|
+
# 值为 None 的参数(如未使用的 data/json/params)不传给 requests,避免干扰 multipart 等场景
|
|
252
|
+
request_obj.update({k: v for k, v in kwargs.items() if v is not None})
|
|
253
|
+
return self.request({"request": request_obj, "app": app})
|
|
254
|
+
|
|
255
|
+
def post(self, app: str | None = None, url: str = "", data: Any = None, json: Any = None,
|
|
256
|
+
**kwargs: Any) -> ResponseUtil:
|
|
257
|
+
"""发送 POST 请求。
|
|
258
|
+
@param app: 应用名称,不传则 url 需为完整地址
|
|
259
|
+
@param url: API 路径
|
|
260
|
+
@param data: 表单数据
|
|
261
|
+
@param json: JSON 数据
|
|
262
|
+
@param kwargs: 其他请求参数
|
|
263
|
+
@return: ResponseUtil 实例
|
|
264
|
+
"""
|
|
265
|
+
return self._make_request("post", app, url, data=data, json=json, **kwargs)
|
|
266
|
+
|
|
267
|
+
def get(self, app: str | None = None, url: str = "", params: Any = None, **kwargs: Any) -> ResponseUtil:
|
|
268
|
+
"""发送 GET 请求。
|
|
269
|
+
@param app: 应用名称,不传则 url 需为完整地址
|
|
270
|
+
@param url: API 路径
|
|
271
|
+
@param params: 查询参数
|
|
272
|
+
@param kwargs: 其他请求参数
|
|
273
|
+
@return: ResponseUtil 实例
|
|
274
|
+
"""
|
|
275
|
+
return self._make_request("get", app, url, params=params, **kwargs)
|
|
276
|
+
|
|
277
|
+
def put(self, app: str | None = None, url: str = "", data: Any = None, **kwargs: Any) -> ResponseUtil:
|
|
278
|
+
"""发送 PUT 请求。
|
|
279
|
+
@param app: 应用名称,不传则 url 需为完整地址
|
|
280
|
+
@param url: API 路径
|
|
281
|
+
@param data: 请求数据
|
|
282
|
+
@param kwargs: 其他请求参数
|
|
283
|
+
@return: ResponseUtil 实例
|
|
284
|
+
"""
|
|
285
|
+
return self._make_request("put", app, url, data=data, **kwargs)
|
|
286
|
+
|
|
287
|
+
def delete(self, app: str | None = None, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
288
|
+
"""发送 DELETE 请求。
|
|
289
|
+
@param app: 应用名称,不传则 url 需为完整地址
|
|
290
|
+
@param url: API 路径
|
|
291
|
+
@param kwargs: 其他请求参数
|
|
292
|
+
@return: ResponseUtil 实例
|
|
293
|
+
"""
|
|
294
|
+
return self._make_request("delete", app, url, **kwargs)
|
|
295
|
+
|
|
296
|
+
def patch(self, app: str | None = None, url: str = "", data: Any = None, json: Any = None,
|
|
297
|
+
**kwargs: Any) -> ResponseUtil:
|
|
298
|
+
"""发送 PATCH 请求。
|
|
299
|
+
@param app: 应用名称,不传则 url 需为完整地址
|
|
300
|
+
@param url: API 路径
|
|
301
|
+
@param data: 请求数据
|
|
302
|
+
@param kwargs: 其他请求参数
|
|
303
|
+
@return: ResponseUtil 实例
|
|
304
|
+
"""
|
|
305
|
+
return self._make_request("patch", app, url, data=data, json=json, **kwargs)
|
|
306
|
+
|
|
307
|
+
def head(self, app: str | None = None, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
308
|
+
"""发送 HEAD 请求。
|
|
309
|
+
@param app: 应用名称,不传则 url 需为完整地址
|
|
310
|
+
@param url: API 路径
|
|
311
|
+
@param kwargs: 其他请求参数
|
|
312
|
+
@return: ResponseUtil 实例
|
|
313
|
+
"""
|
|
314
|
+
return self._make_request("head", app, url, **kwargs)
|
|
315
|
+
|
|
316
|
+
def options(self, app: str | None = None, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
317
|
+
"""发送 OPTIONS 请求。
|
|
318
|
+
@param app: 应用名称,不传则 url 需为完整地址
|
|
319
|
+
@param url: API 路径
|
|
320
|
+
@param kwargs: 其他请求参数
|
|
321
|
+
@return: ResponseUtil 实例
|
|
322
|
+
"""
|
|
323
|
+
return self._make_request("options", app, url, **kwargs)
|
|
324
|
+
|
|
325
|
+
def update_headers(self, headers: dict[str, str]) -> None:
|
|
326
|
+
"""更新客户端默认请求头。
|
|
327
|
+
@param headers: 要更新的请求头字典
|
|
328
|
+
"""
|
|
329
|
+
self.headers.update(headers)
|
|
330
|
+
|
|
331
|
+
@staticmethod
|
|
332
|
+
def json(dic: Any) -> str | Any:
|
|
333
|
+
"""将字典转换为 JSON 字符串(带异常保护)。
|
|
334
|
+
@param dic: 字典数据
|
|
335
|
+
@return: JSON 字符串,转换失败则返回原数据
|
|
336
|
+
"""
|
|
337
|
+
try:
|
|
338
|
+
return built_json.dumps(dic)
|
|
339
|
+
except Exception: # 序列化失败时返回原始数据
|
|
340
|
+
return dic
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""MQ 消息队列模块。
|
|
2
|
+
|
|
3
|
+
提供 MQ 连接池和客户端,支持消息发布和消费。
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
import pika
|
|
11
|
+
from pika.exceptions import AMQPError
|
|
12
|
+
|
|
13
|
+
logging.getLogger("pika").setLevel(logging.CRITICAL)
|
|
14
|
+
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from framework.exceptions import MQError
|
|
18
|
+
from framework.utils.log_util import logger
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LazyMQPool:
|
|
22
|
+
"""MQ 连接池,支持多 virtual_host,每个 vhost 独立连接,按 exchange 分 channel,线程安全。"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, mq_config: dict):
|
|
25
|
+
"""
|
|
26
|
+
初始化 MQ 连接池。
|
|
27
|
+
|
|
28
|
+
:param mq_config: MQ 配置字典,含 host、port、credentials、virtual_hosts
|
|
29
|
+
"""
|
|
30
|
+
host = mq_config.get("host", "localhost")
|
|
31
|
+
port = mq_config.get("port", 5672)
|
|
32
|
+
default_creds = mq_config.get("credentials", {})
|
|
33
|
+
vhosts_conf = mq_config.get("virtual_hosts", {})
|
|
34
|
+
|
|
35
|
+
self._host = host
|
|
36
|
+
self._port = port
|
|
37
|
+
self._vhost_params: dict[str, pika.ConnectionParameters] = {}
|
|
38
|
+
self._vhost_exchanges: dict[str, dict] = {}
|
|
39
|
+
|
|
40
|
+
for vhost, conf in vhosts_conf.items():
|
|
41
|
+
creds = conf.get("credentials", default_creds)
|
|
42
|
+
params = {"host": host, "port": port, "virtual_host": vhost}
|
|
43
|
+
if creds:
|
|
44
|
+
params["credentials"] = pika.PlainCredentials(
|
|
45
|
+
str(creds.get("username", "guest")),
|
|
46
|
+
str(creds.get("password", "guest")),
|
|
47
|
+
)
|
|
48
|
+
self._vhost_params[vhost] = pika.ConnectionParameters(**params)
|
|
49
|
+
self._vhost_exchanges[vhost] = conf.get("exchanges", {})
|
|
50
|
+
|
|
51
|
+
self._connections: dict[str, pika.BlockingConnection] = {}
|
|
52
|
+
self._clients: dict[str, dict[str, "MQClient"]] = {}
|
|
53
|
+
self._lock = threading.Lock()
|
|
54
|
+
|
|
55
|
+
def _ensure_connection(self, vhost: str = "/") -> None:
|
|
56
|
+
"""确保指定 vhost 的连接可用,断开时自动重连。"""
|
|
57
|
+
if vhost not in self._vhost_params:
|
|
58
|
+
raise MQError(
|
|
59
|
+
f"vhost '{vhost}' 未配置,当前已配置: {list(self._vhost_params.keys())}"
|
|
60
|
+
)
|
|
61
|
+
if vhost not in self._connections or self._connections[vhost].is_closed:
|
|
62
|
+
with self._lock:
|
|
63
|
+
if vhost not in self._connections or self._connections[vhost].is_closed:
|
|
64
|
+
try:
|
|
65
|
+
self._connections[vhost] = pika.BlockingConnection(self._vhost_params[vhost])
|
|
66
|
+
logger.info(f"MQ连接成功: {self._host}:{self._port}, vhost={vhost}")
|
|
67
|
+
except Exception as e:
|
|
68
|
+
logger.error(f"MQ连接失败: {self._host}:{self._port}, vhost={vhost}, {e}")
|
|
69
|
+
raise
|
|
70
|
+
|
|
71
|
+
def get(self, exchange_name: str, vhost: str = "/") -> "MQClient":
|
|
72
|
+
"""
|
|
73
|
+
获取指定 vhost 下指定 exchange 的 MQ 客户端。
|
|
74
|
+
|
|
75
|
+
:param exchange_name: 交换机名称
|
|
76
|
+
:param vhost: 虚拟主机名称,默认 "/"
|
|
77
|
+
:return: MQClient 实例
|
|
78
|
+
"""
|
|
79
|
+
self._ensure_connection(vhost)
|
|
80
|
+
if vhost not in self._clients:
|
|
81
|
+
self._clients[vhost] = {}
|
|
82
|
+
if exchange_name not in self._clients[vhost]:
|
|
83
|
+
with self._lock:
|
|
84
|
+
if exchange_name not in self._clients[vhost]:
|
|
85
|
+
conf = self._vhost_exchanges.get(vhost, {}).get(exchange_name)
|
|
86
|
+
channel = self._connections[vhost].channel()
|
|
87
|
+
if conf is None:
|
|
88
|
+
logger.warning(
|
|
89
|
+
f"Exchange '{exchange_name}' 未在 database.{{env}}.yaml vhost '{vhost}' 中定义,"
|
|
90
|
+
f"当前已配置: {list(self._vhost_exchanges.get(vhost, {}).keys())}"
|
|
91
|
+
)
|
|
92
|
+
channel.exchange_declare(exchange=exchange_name, passive=True)
|
|
93
|
+
else:
|
|
94
|
+
channel.exchange_declare(
|
|
95
|
+
exchange=exchange_name,
|
|
96
|
+
exchange_type=conf.get("type", "topic"),
|
|
97
|
+
durable=conf.get("durable", True),
|
|
98
|
+
auto_delete=conf.get("auto_delete", False),
|
|
99
|
+
)
|
|
100
|
+
self._clients[vhost][exchange_name] = MQClient(channel, exchange_name)
|
|
101
|
+
return self._clients[vhost][exchange_name]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class MQClient:
|
|
105
|
+
"""MQ 客户端,每个实例持有一个 channel。"""
|
|
106
|
+
|
|
107
|
+
def __init__(self, channel, exchange_name):
|
|
108
|
+
self._channel = channel
|
|
109
|
+
self._exchange_name = exchange_name
|
|
110
|
+
|
|
111
|
+
def publish(self, message: dict | str, routing_key: str = "", content_type: str | None = None) -> None:
|
|
112
|
+
"""
|
|
113
|
+
发布消息到 exchange。
|
|
114
|
+
|
|
115
|
+
:param message: 消息内容(str 或 dict,dict 自动序列化为 JSON)
|
|
116
|
+
:param routing_key: 路由键
|
|
117
|
+
:param content_type: 消息类型,不传则 dict→application/json,str→text/plain
|
|
118
|
+
"""
|
|
119
|
+
if isinstance(message, dict):
|
|
120
|
+
body = json.dumps(message, ensure_ascii=False)
|
|
121
|
+
content_type = content_type or "application/json"
|
|
122
|
+
else:
|
|
123
|
+
body = str(message)
|
|
124
|
+
content_type = content_type or "text/plain"
|
|
125
|
+
|
|
126
|
+
properties = pika.BasicProperties(content_type=content_type)
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
self._channel.basic_publish(
|
|
130
|
+
exchange=self._exchange_name,
|
|
131
|
+
routing_key=routing_key,
|
|
132
|
+
body=body.encode(),
|
|
133
|
+
properties=properties,
|
|
134
|
+
)
|
|
135
|
+
logger.info(f"MQ发送: exchange={self._exchange_name}, "
|
|
136
|
+
f"routing_key={routing_key}, message={body}")
|
|
137
|
+
except AMQPError as e:
|
|
138
|
+
raise MQError(f"MQ发送失败, exchange={self._exchange_name}: {e}")
|
|
139
|
+
|
|
140
|
+
def consume(self, routing_key: str = "#", timeout: int = 10, callback: Any = None) -> dict | str | None:
|
|
141
|
+
"""
|
|
142
|
+
消费一条 MQ 消息(通过临时队列订阅,用完自动删除)。
|
|
143
|
+
|
|
144
|
+
:param routing_key: 绑定键,默认 # 匹配所有
|
|
145
|
+
:param timeout: 超时时间(秒)
|
|
146
|
+
:param callback: 过滤回调,接收消息体,返回 True 表示命中
|
|
147
|
+
:return: 消息体(dict/str)或 None(超时)
|
|
148
|
+
"""
|
|
149
|
+
conn = self._channel.connection
|
|
150
|
+
temp_ch = conn.channel()
|
|
151
|
+
result = temp_ch.queue_declare(queue="", exclusive=True, auto_delete=True)
|
|
152
|
+
temp_queue = result.method.queue
|
|
153
|
+
temp_ch.queue_bind(exchange=self._exchange_name, queue=temp_queue, routing_key=routing_key)
|
|
154
|
+
logger.info(f"MQ监听: exchange={self._exchange_name}, routing_key={routing_key}, queue={temp_queue}")
|
|
155
|
+
|
|
156
|
+
end_time = time.time() + timeout
|
|
157
|
+
matched = None
|
|
158
|
+
|
|
159
|
+
def _on_message(ch, method, properties, body):
|
|
160
|
+
nonlocal matched
|
|
161
|
+
try:
|
|
162
|
+
msg = json.loads(body)
|
|
163
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
164
|
+
msg = body.decode()
|
|
165
|
+
if callback is None or callback(msg):
|
|
166
|
+
matched = msg
|
|
167
|
+
ch.stop_consuming()
|
|
168
|
+
|
|
169
|
+
temp_ch.basic_consume(queue=temp_queue, on_message_callback=_on_message)
|
|
170
|
+
try:
|
|
171
|
+
while time.time() < end_time and matched is None:
|
|
172
|
+
conn.process_data_events(time_limit=1)
|
|
173
|
+
except Exception:
|
|
174
|
+
pass
|
|
175
|
+
temp_ch.queue_delete(queue=temp_queue)
|
|
176
|
+
temp_ch.close()
|
|
177
|
+
logger.info(f"MQ接收: exchange={self._exchange_name}, routing_key={routing_key}, message={matched}")
|
|
178
|
+
return matched
|