sycommon-python-lib 0.1.28__py3-none-any.whl → 0.1.30__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.

Potentially problematic release.


This version of sycommon-python-lib might be problematic. Click here for more details.

sycommon/synacos/feign.py CHANGED
@@ -1,8 +1,6 @@
1
1
  import io
2
2
  import os
3
3
  import time
4
- import inspect
5
- from urllib.parse import urljoin
6
4
 
7
5
  import aiohttp
8
6
  from sycommon.logging.kafka_log import SYLogger
@@ -14,397 +12,6 @@ from sycommon.synacos.nacos_service import NacosService
14
12
  方式二: 使用 feign 函数
15
13
  """
16
14
 
17
- # 示例Feign客户端接口
18
- # 1. 定义完整的Feign客户端接口
19
- # @feign_client(service_name="product-service", path_prefix="/api/v2")
20
- # class ProductServiceClient:
21
- # """商品服务Feign客户端示例,涵盖所有参数类型"""
22
- #
23
- # # ------------------------------
24
- # # 场景1: Path参数 + Query参数
25
- # # 请求示例: GET /products/{product_id}/reviews?status=APPROVED&page=1&size=10
26
- # # ------------------------------
27
- # @feign_request("GET", "/products/{product_id}/reviews")
28
- # async def get_product_reviews(
29
- # self,
30
- # product_id: int, # Path参数 (URL路径中的占位符)
31
- # status: Optional[str] = None, # Query参数 (URL查询字符串)
32
- # page: int = 1, # Query参数 (默认值)
33
- # size: int = 10 # Query参数 (默认值)
34
- # ) -> Dict[str, Any]:
35
- # """获取商品评价列表"""
36
- # pass
37
- #
38
- # # ------------------------------
39
- # # 场景2: 仅Query参数
40
- # # 请求示例: GET /products?category=electronics&min_price=100&max_price=500&sort=price_asc
41
- # # ------------------------------
42
- # @feign_request("GET", "/products")
43
- # async def search_products(
44
- # self,
45
- # category: str, # 必选Query参数
46
- # min_price: Optional[float] = None, # 可选Query参数
47
- # max_price: Optional[float] = None, # 可选Query参数
48
- # sort: str = "created_desc" # 带默认值的Query参数
49
- # ) -> Dict[str, Any]:
50
- # """搜索商品(仅查询参数)"""
51
- # pass
52
- #
53
- # # ------------------------------
54
- # # 场景3: JSON Body参数 (POST)
55
- # # 请求示例: POST /products (请求体为JSON)
56
- # # ------------------------------
57
- # @feign_request("POST", "/products", headers={"s-y-version": "2.1"})
58
- # async def create_product(
59
- # self,
60
- # product_data: Dict[str, Any] # JSON请求体
61
- # ) -> Dict[str, Any]:
62
- # """创建商品(JSON请求体)"""
63
- # pass
64
- #
65
- # # ------------------------------
66
- # # 场景4: Path参数 + JSON Body (PUT)
67
- # # 请求示例: PUT /products/{product_id} (请求体为JSON)
68
- # # ------------------------------
69
- # @feign_request("PUT", "/products/{product_id}")
70
- # async def update_product(
71
- # self,
72
- # product_id: int, # Path参数
73
- # update_data: Dict[str, Any] # JSON请求体
74
- # ) -> Dict[str, Any]:
75
- # """更新商品信息"""
76
- # pass
77
- #
78
- # # ------------------------------
79
- # # 场景5: FormData表单提交 (x-www-form-urlencoded)
80
- # # 请求示例: POST /products/batch-status (表单字段)
81
- # # ------------------------------
82
- # @feign_request(
83
- # "POST",
84
- # "/products/batch-status",
85
- # headers={"Content-Type": "application/x-www-form-urlencoded"}
86
- # )
87
- # async def batch_update_status(
88
- # self,
89
- # product_ids: str, # 表单字段 (多个ID用逗号分隔)
90
- # status: str, # 表单字段 (目标状态)
91
- # operator: str # 表单字段 (操作人)
92
- # ) -> Dict[str, Any]:
93
- # """批量更新商品状态(表单提交)"""
94
- # pass
95
- #
96
- # # ------------------------------
97
- # # 场景6: 文件上传 + 表单字段混合
98
- # # 请求示例: POST /products/{product_id}/images (multipart/form-data)
99
- # # ------------------------------
100
- # @feign_upload(field_name="image_file") # 指定文件表单字段名
101
- # @feign_request("POST", "/products/{product_id}/images")
102
- # async def upload_product_image(
103
- # self,
104
- # product_id: int, # Path参数
105
- # file_path: str, # 本地文件路径(会被转为文件上传)
106
- # image_type: str, # 表单字段(图片类型)
107
- # is_primary: bool = False, # 表单字段(是否主图)
108
- # remark: Optional[str] = None # 可选表单字段
109
- # ) -> Dict[str, Any]:
110
- # """上传商品图片(文件+表单字段)"""
111
- # pass
112
- #
113
- # # ------------------------------
114
- # # 场景7: 多Path参数 + DELETE请求
115
- # # 请求示例: DELETE /products/{product_id}/skus/{sku_id}
116
- # # ------------------------------
117
- # @feign_request("DELETE", "/products/{product_id}/skus/{sku_id}")
118
- # async def delete_product_sku(
119
- # self,
120
- # product_id: int, # Path参数1
121
- # sku_id: int # Path参数2
122
- # ) -> Dict[str, Any]:
123
- # """删除商品SKU(多路径参数)"""
124
- # pass
125
- #
126
- # # ------------------------------
127
- # # 场景8: 复杂JSON Body + Query参数
128
- # # 请求示例: POST /products/filter?include_out_of_stock=false
129
- # # ------------------------------
130
- # @feign_request("POST", "/products/filter")
131
- # async def advanced_filter(
132
- # self,
133
- # filter_condition: Dict[str, Any], # JSON请求体(复杂筛选条件)
134
- # include_out_of_stock: bool = False, # Query参数
135
- # page: int = 1, # Query参数
136
- # size: int = 20 # Query参数
137
- # ) -> Dict[str, Any]:
138
- # """高级筛选商品(JSON体+查询参数)"""
139
- # pass
140
- #
141
- #
142
- # # 2. 完整调用示例
143
- # async def feign_complete_demo():
144
- # # ------------------------------
145
- # # 调用场景1: Path参数 + Query参数
146
- # # ------------------------------
147
- # reviews = await ProductServiceClient().get_product_reviews(
148
- # product_id=10086, # Path参数
149
- # status="APPROVED", # Query参数
150
- # page=1,
151
- # size=20
152
- # )
153
- # print(f"场景1 - 商品评价: {reviews.get('total', 0)}条评价")
154
- #
155
- # # ------------------------------
156
- # # 调用场景2: 仅Query参数
157
- # # ------------------------------
158
- # electronics = await ProductServiceClient().search_products(
159
- # category="electronics", # 必选Query
160
- # min_price=1000,
161
- # max_price=5000,
162
- # sort="price_asc"
163
- # )
164
- # print(f"场景2 - 搜索结果: {len(electronics.get('items', []))}个商品")
165
- #
166
- # # ------------------------------
167
- # # 调用场景3: JSON Body参数 (POST)
168
- # # ------------------------------
169
- # new_product = await ProductServiceClient().create_product({
170
- # "name": "无线蓝牙耳机",
171
- # "category": "electronics",
172
- # "price": 299.99,
173
- # "stock": 500,
174
- # "attributes": {
175
- # "brand": "Feign",
176
- # "battery_life": "24h"
177
- # }
178
- # })
179
- # print(f"场景3 - 新建商品: ID={new_product.get('id')}")
180
- # product_id = new_product.get('id') # 用于后续示例
181
- #
182
- # # ------------------------------
183
- # # 调用场景4: Path参数 + JSON Body (PUT)
184
- # # ------------------------------
185
- # if product_id:
186
- # updated = await ProductServiceClient().update_product(
187
- # product_id=product_id,
188
- # update_data={
189
- # "price": 279.99, # 降价
190
- # "stock": 600
191
- # }
192
- # )
193
- # print(f"场景4 - 商品更新: 状态={updated.get('success')}")
194
- #
195
- # # ------------------------------
196
- # # 调用场景5: FormData表单提交
197
- # # ------------------------------
198
- # batch_result = await ProductServiceClient().batch_update_status(
199
- # product_ids="1001,1002,1003", # 多个ID用逗号分隔
200
- # status="ON_SALE",
201
- # operator="system"
202
- # )
203
- # print(f"场景5 - 批量更新: 成功{batch_result.get('success_count')}个")
204
- #
205
- # # ------------------------------
206
- # # 调用场景6: 文件上传 + 表单字段
207
- # # ------------------------------
208
- # if product_id:
209
- # upload_result = await ProductServiceClient().upload_product_image(
210
- # product_id=product_id,
211
- # file_path="/tmp/product_main.jpg", # 本地图片路径
212
- # image_type="main",
213
- # is_primary=True,
214
- # remark="商品主图"
215
- # )
216
- # print(f"场景6 - 图片上传: URL={upload_result.get('image_url')}")
217
- #
218
- # # ------------------------------
219
- # # 调用场景7: 多Path参数 + DELETE
220
- # # ------------------------------
221
- # delete_result = await ProductServiceClient().delete_product_sku(
222
- # product_id=10086,
223
- # sku_id=5001
224
- # )
225
- # print(f"场景7 - 删除SKU: {delete_result.get('message')}")
226
- #
227
- # # ------------------------------
228
- # # 调用场景8: 复杂JSON Body + Query参数
229
- # # ------------------------------
230
- # filtered = await ProductServiceClient().advanced_filter(
231
- # filter_condition={ # 复杂JSON条件
232
- # "categories": ["electronics", "home"],
233
- # "price_range": {"min": 500, "max": 3000},
234
- # "tags": ["new", "promotion"]
235
- # },
236
- # include_out_of_stock=False, # Query参数
237
- # page=1,
238
- # size=10
239
- # )
240
- # print(f"场景8 - 高级筛选: {filtered.get('total')}个匹配商品")
241
-
242
-
243
- def feign_client(service_name: str, path_prefix: str = "", default_timeout: float | None = None):
244
- """Feign客户端装饰器,每次请求后自动关闭会话"""
245
- def decorator(cls):
246
- class FeignWrapper:
247
- def __init__(self):
248
- self.service_name = service_name
249
- self.path_prefix = path_prefix
250
- self.default_timeout = default_timeout
251
- self.nacos_manager = None # 延迟初始化Nacos
252
- self.session = None # 延迟初始化aiohttp会话
253
-
254
- def __getattr__(self, name):
255
- """动态获取方法并包装为Feign调用,请求后自动关闭会话"""
256
- func = getattr(cls, name)
257
-
258
- async def wrapper(*args, **kwargs):
259
- # 确保会话初始化
260
- if self.session is None:
261
- self.session = aiohttp.ClientSession()
262
- if self.nacos_manager is None:
263
- self.nacos_manager = NacosService(None)
264
-
265
- try:
266
- # 1. 解析参数
267
- sig = inspect.signature(func)
268
- param_names = list(sig.parameters.keys())
269
- try:
270
- if param_names and param_names[0] == 'self':
271
- bound_args = sig.bind(self, *args, **kwargs)
272
- else:
273
- bound_args = sig.bind(*args, **kwargs)
274
- bound_args.apply_defaults()
275
- params = dict(bound_args.arguments)
276
- params.pop('self', None)
277
- SYLogger.debug(f"解析参数: {params}")
278
- except TypeError as e:
279
- SYLogger.error(f"参数绑定失败: {str(e)}")
280
- raise
281
-
282
- # 2. 构建请求
283
- request_meta = getattr(func, "_feign_meta", {})
284
- method = request_meta.get("method", "GET")
285
- path = request_meta.get("path", "")
286
- headers = request_meta.get("headers", {}).copy()
287
- timeout = kwargs.pop('timeout', self.default_timeout)
288
-
289
- full_path = f"{self.path_prefix}{path}"
290
- for param_name, param_value in params.items():
291
- if param_value is not None:
292
- full_path = full_path.replace(
293
- f"{{{param_name}}}", str(param_value))
294
-
295
- is_json_request = method.upper() in ["POST", "PUT", "PATCH"] and \
296
- not request_meta.get("is_upload", False)
297
- if is_json_request and "Content-Type" not in headers:
298
- headers["Content-Type"] = "application/json"
299
-
300
- # 3. 服务发现
301
- version = headers.get('s-y-version')
302
- instances = self.nacos_manager.get_service_instances(
303
- self.service_name, target_version=version)
304
- if not instances:
305
- raise RuntimeError(
306
- f"未找到服务 {self.service_name} 的健康实例")
307
-
308
- instance = instances[int(time.time()) % len(instances)]
309
- base_url = f"http://{instance['ip']}:{instance['port']}"
310
- url = urljoin(base_url, full_path)
311
- SYLogger.info(f"请求: {method} {url}")
312
-
313
- # 4. 准备请求参数
314
- query_params = {k: v for k, v in params.items()
315
- if f"{{{k}}}" not in path and v is not None}
316
- request_data = None
317
- files = None
318
-
319
- if request_meta.get("is_upload", False):
320
- files = aiohttp.FormData()
321
- file_path = params.get('file_path')
322
- if file_path and os.path.exists(file_path):
323
- file_field = request_meta.get(
324
- "upload_field", "file")
325
- with open(file_path, 'rb') as f:
326
- files.add_field(
327
- file_field,
328
- f.read(),
329
- filename=os.path.basename(file_path)
330
- )
331
- for key, value in params.items():
332
- if key != 'file_path' and value is not None:
333
- files.add_field(key, str(value))
334
- headers.pop('Content-Type', None)
335
- elif is_json_request:
336
- body_params = [k for k in params if k not in query_params
337
- and f"{{{k}}}" not in path]
338
- if body_params:
339
- request_data = params[body_params[0]] if len(body_params) == 1 else \
340
- {k: params[k] for k in body_params}
341
-
342
- # 5. 发送请求并获取响应
343
- async with self.session.request(
344
- method=method,
345
- url=url,
346
- headers=headers,
347
- params=query_params,
348
- json=request_data if not files else None,
349
- data=files,
350
- timeout=timeout
351
- ) as response:
352
- return await self._handle_response(response)
353
-
354
- finally:
355
- # 请求完成后自动关闭会话
356
- if self.session:
357
- await self.session.close()
358
- self.session = None # 重置会话,下次调用重新创建
359
- SYLogger.info(
360
- f"自动关闭aiohttp会话: {self.service_name}")
361
-
362
- return wrapper
363
-
364
- async def _handle_response(self, response):
365
- """处理响应结果(保持不变)"""
366
- status = response.status
367
- if 200 <= status < 300:
368
- content_type = response.headers.get('Content-Type', '')
369
- if 'application/json' in content_type:
370
- return await response.json()
371
- else:
372
- return await response.read()
373
- else:
374
- error_msg = await response.text()
375
- SYLogger.error(f"响应错误: {status} - {error_msg}")
376
- raise RuntimeError(f"HTTP {status}: {error_msg}")
377
-
378
- return FeignWrapper
379
- return decorator
380
-
381
-
382
- def feign_request(method: str, path: str, headers: dict = None):
383
- """定义请求元数据的装饰器"""
384
- def decorator(func):
385
- func._feign_meta = {
386
- "method": method.upper(),
387
- "path": path,
388
- "headers": headers.copy() if headers else {}
389
- }
390
- return func
391
- return decorator
392
-
393
-
394
- def feign_upload(field_name: str = "file"):
395
- """处理文件上传的装饰器"""
396
- def decorator(func):
397
- async def wrapper(*args, **kwargs):
398
- file_path = kwargs.get('file_path')
399
- if not file_path or not os.path.exists(file_path):
400
- raise ValueError(f"文件路径不存在: {file_path}")
401
- with open(file_path, 'rb') as f:
402
- files = {field_name: (os.path.basename(file_path), f.read())}
403
- kwargs['files'] = files
404
- return await func(*args, **kwargs)
405
- return wrapper
406
- return decorator
407
-
408
15
 
409
16
  async def feign(service_name, api_path, method='GET', params=None, headers=None, file_path=None,
410
17
  path_params=None, body=None, files=None, form_data=None, timeout=None):
@@ -457,8 +64,25 @@ async def feign(service_name, api_path, method='GET', params=None, headers=None,
457
64
  for key, value in form_data.items():
458
65
  data.add_field(key, value)
459
66
  if files:
460
- for field_name, (filename, content) in files.items():
461
- data.add_field(field_name, content, filename=filename)
67
+ # 兼容处理:同时支持字典(单文件)和列表(多文件)
68
+ if isinstance(files, dict):
69
+ # 处理原有字典格式(单文件)
70
+ # 字典格式:{field_name: (filename, content)}
71
+ for field_name, (filename, content) in files.items():
72
+ data.add_field(field_name, content,
73
+ filename=filename)
74
+ elif isinstance(files, list):
75
+ # 处理新列表格式(多文件)
76
+ # 列表格式:[(field_name, filename, content), ...]
77
+ for item in files:
78
+ if len(item) != 3:
79
+ raise ValueError(
80
+ f"列表元素格式错误,需为 (field_name, filename, content),实际为 {item}")
81
+ field_name, filename, content = item
82
+ data.add_field(field_name, content,
83
+ filename=filename)
84
+ else:
85
+ raise TypeError(f"files 参数必须是字典或列表,实际为 {type(files)}")
462
86
  if file_path:
463
87
  filename = os.path.basename(file_path)
464
88
  with open(file_path, 'rb') as f: