huace-aigc-auth-client 1.1.33__py3-none-any.whl → 1.1.35__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.
- huace_aigc_auth_client/__init__.py +14 -2
- huace_aigc_auth_client/auth_request.py +340 -64
- {huace_aigc_auth_client-1.1.33.dist-info → huace_aigc_auth_client-1.1.35.dist-info}/METADATA +354 -1
- {huace_aigc_auth_client-1.1.33.dist-info → huace_aigc_auth_client-1.1.35.dist-info}/RECORD +7 -7
- {huace_aigc_auth_client-1.1.33.dist-info → huace_aigc_auth_client-1.1.35.dist-info}/WHEEL +0 -0
- {huace_aigc_auth_client-1.1.33.dist-info → huace_aigc_auth_client-1.1.35.dist-info}/licenses/LICENSE +0 -0
- {huace_aigc_auth_client-1.1.33.dist-info → huace_aigc_auth_client-1.1.35.dist-info}/top_level.txt +0 -0
|
@@ -67,7 +67,13 @@ from .api_stats_collector import (
|
|
|
67
67
|
|
|
68
68
|
from .auth_request import (
|
|
69
69
|
auth_request,
|
|
70
|
-
|
|
70
|
+
auth_request_get,
|
|
71
|
+
auth_request_post,
|
|
72
|
+
AuthSession,
|
|
73
|
+
async_auth_httpx_request,
|
|
74
|
+
async_auth_httpx_request_get,
|
|
75
|
+
async_auth_httpx_request_post,
|
|
76
|
+
AsyncAuthClient,
|
|
71
77
|
)
|
|
72
78
|
|
|
73
79
|
from .legacy_adapter import (
|
|
@@ -215,6 +221,12 @@ __all__ = [
|
|
|
215
221
|
"stop_api_stats_collector",
|
|
216
222
|
# 认证请求封装
|
|
217
223
|
"auth_request",
|
|
224
|
+
"auth_request_get",
|
|
225
|
+
"auth_request_post",
|
|
226
|
+
"AuthSession",
|
|
218
227
|
"async_auth_httpx_request",
|
|
228
|
+
"async_auth_httpx_request_get",
|
|
229
|
+
"async_auth_httpx_request_post",
|
|
230
|
+
"AsyncAuthClient",
|
|
219
231
|
]
|
|
220
|
-
__version__ = "1.1.
|
|
232
|
+
__version__ = "1.1.35"
|
|
@@ -29,6 +29,80 @@ def setLogger(log):
|
|
|
29
29
|
global logger
|
|
30
30
|
logger = log
|
|
31
31
|
|
|
32
|
+
def _report_stats(
|
|
33
|
+
url: str,
|
|
34
|
+
method: str,
|
|
35
|
+
response: Optional[Response],
|
|
36
|
+
response_time: float,
|
|
37
|
+
error_message: Optional[str],
|
|
38
|
+
request_context: Optional[Dict[str, Any]],
|
|
39
|
+
headers: Optional[Dict[str, str]],
|
|
40
|
+
params: Optional[Dict[str, Any]],
|
|
41
|
+
json_data: Optional[Dict[str, Any]],
|
|
42
|
+
form_data: Optional[Union[Dict[str, Any], str, bytes]]
|
|
43
|
+
):
|
|
44
|
+
"""
|
|
45
|
+
上报统计信息到远程服务
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
url: 请求 URL
|
|
49
|
+
method: HTTP 方法
|
|
50
|
+
response: 响应对象
|
|
51
|
+
response_time: 响应时间
|
|
52
|
+
error_message: 错误信息
|
|
53
|
+
request_context: 请求上下文
|
|
54
|
+
params: 查询参数
|
|
55
|
+
json_data: JSON 数据
|
|
56
|
+
form_data: 表单数据
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
# 获取统计收集器
|
|
60
|
+
collector = get_api_stats_collector()
|
|
61
|
+
if not collector:
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
# 获取 token
|
|
65
|
+
token = request_context.get('token') if request_context else None
|
|
66
|
+
if not token:
|
|
67
|
+
return
|
|
68
|
+
|
|
69
|
+
# 解析 URL 获取路径
|
|
70
|
+
from urllib.parse import urlparse
|
|
71
|
+
parsed_url = urlparse(url)
|
|
72
|
+
api_path = parsed_url.path or '/'
|
|
73
|
+
# 带上协议和域名
|
|
74
|
+
api_path = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path or '/'}"
|
|
75
|
+
|
|
76
|
+
# 获取状态码
|
|
77
|
+
status_code = response.status_code if response else 500
|
|
78
|
+
|
|
79
|
+
# 构建请求参数(与 api_stats_collector 格式一致)
|
|
80
|
+
request_params = {
|
|
81
|
+
'query_params': params or {},
|
|
82
|
+
'headers': headers
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
# 添加请求体数据
|
|
86
|
+
if json_data:
|
|
87
|
+
request_params['request_body'] = json_data
|
|
88
|
+
elif isinstance(form_data, dict):
|
|
89
|
+
request_params['form_params'] = form_data
|
|
90
|
+
|
|
91
|
+
# 收集统计
|
|
92
|
+
collector.collect(
|
|
93
|
+
api_path=api_path,
|
|
94
|
+
api_method=method.upper(),
|
|
95
|
+
status_code=status_code,
|
|
96
|
+
response_time=response_time,
|
|
97
|
+
token=token,
|
|
98
|
+
error_message=error_message,
|
|
99
|
+
request_params=request_params
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
except Exception as e:
|
|
103
|
+
# 静默失败,不影响主流程
|
|
104
|
+
logger.debug(f"统计上报失败: {e}")
|
|
105
|
+
|
|
32
106
|
def auth_request(
|
|
33
107
|
method: str,
|
|
34
108
|
url: str,
|
|
@@ -173,80 +247,195 @@ def auth_request(
|
|
|
173
247
|
form_data=data
|
|
174
248
|
)
|
|
175
249
|
|
|
250
|
+
def auth_request_get(
|
|
251
|
+
url: str,
|
|
252
|
+
params: Optional[Dict[str, Any]] = None,
|
|
253
|
+
headers: Optional[Dict[str, str]] = None,
|
|
254
|
+
**kwargs
|
|
255
|
+
) -> Response:
|
|
256
|
+
"""
|
|
257
|
+
GET 请求快捷方法
|
|
258
|
+
|
|
259
|
+
Args:
|
|
260
|
+
url: 请求 URL
|
|
261
|
+
params: URL 查询参数
|
|
262
|
+
headers: 请求头
|
|
263
|
+
**kwargs: 其他 auth_request 支持的参数
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
Response: 响应对象
|
|
267
|
+
"""
|
|
268
|
+
return auth_request('GET', url, params=params, headers=headers, **kwargs)
|
|
176
269
|
|
|
177
|
-
def
|
|
270
|
+
def auth_request_post(
|
|
178
271
|
url: str,
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
params: Optional[Dict[str, Any]],
|
|
186
|
-
json_data: Optional[Dict[str, Any]],
|
|
187
|
-
form_data: Optional[Union[Dict[str, Any], str, bytes]]
|
|
188
|
-
):
|
|
272
|
+
data: Optional[Union[Dict[str, Any], str, bytes]] = None,
|
|
273
|
+
json: Optional[Dict[str, Any]] = None,
|
|
274
|
+
params: Optional[Dict[str, Any]] = None,
|
|
275
|
+
headers: Optional[Dict[str, str]] = None,
|
|
276
|
+
**kwargs
|
|
277
|
+
) -> Response:
|
|
189
278
|
"""
|
|
190
|
-
|
|
279
|
+
POST 请求快捷方法
|
|
191
280
|
|
|
192
281
|
Args:
|
|
193
282
|
url: 请求 URL
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
283
|
+
data: 请求体数据 (form-data 或 raw)
|
|
284
|
+
json: JSON 请求体数据
|
|
285
|
+
params: URL 查询参数
|
|
286
|
+
headers: 请求头
|
|
287
|
+
**kwargs: 其他 auth_request 支持的参数
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
Response: 响应对象
|
|
202
291
|
"""
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
#
|
|
219
|
-
|
|
292
|
+
return auth_request('POST', url, data=data, json=json, params=params, headers=headers, **kwargs)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# ============ Session 封装(支持连接池) ============
|
|
296
|
+
|
|
297
|
+
class AuthSession(requests.Session):
|
|
298
|
+
"""
|
|
299
|
+
认证 Session 类(支持连接池)
|
|
300
|
+
|
|
301
|
+
继承 requests.Session,自动添加认证信息和统计上报
|
|
302
|
+
支持连接池,提升性能
|
|
303
|
+
|
|
304
|
+
使用示例:
|
|
305
|
+
from huace_aigc_auth_client import AuthSession, set_request_context
|
|
306
|
+
|
|
307
|
+
# 设置请求上下文
|
|
308
|
+
set_request_context(
|
|
309
|
+
app_id='your-app-id',
|
|
310
|
+
app_secret='your-app-secret',
|
|
311
|
+
token='user-token'
|
|
312
|
+
)
|
|
220
313
|
|
|
221
|
-
#
|
|
222
|
-
|
|
314
|
+
# 创建 Session(自动启用连接池)
|
|
315
|
+
with AuthSession() as session:
|
|
316
|
+
# GET 请求
|
|
317
|
+
response = session.get('https://api.example.com/users')
|
|
318
|
+
|
|
319
|
+
# POST 请求
|
|
320
|
+
response = session.post(
|
|
321
|
+
'https://api.example.com/users',
|
|
322
|
+
json={'name': 'John'}
|
|
323
|
+
)
|
|
324
|
+
"""
|
|
325
|
+
|
|
326
|
+
def request(
|
|
327
|
+
self,
|
|
328
|
+
method: str,
|
|
329
|
+
url: str,
|
|
330
|
+
params: Optional[Dict[str, Any]] = None,
|
|
331
|
+
data: Optional[Union[Dict[str, Any], str, bytes]] = None,
|
|
332
|
+
headers: Optional[Dict[str, str]] = None,
|
|
333
|
+
cookies: Optional[Dict[str, str]] = None,
|
|
334
|
+
files: Optional[Dict[str, Any]] = None,
|
|
335
|
+
auth: Optional[tuple] = None,
|
|
336
|
+
timeout: Optional[Union[float, tuple]] = None,
|
|
337
|
+
allow_redirects: bool = True,
|
|
338
|
+
proxies: Optional[Dict[str, str]] = None,
|
|
339
|
+
hooks: Optional[Dict[str, Any]] = None,
|
|
340
|
+
stream: bool = False,
|
|
341
|
+
verify: Optional[Union[bool, str]] = None,
|
|
342
|
+
cert: Optional[Union[str, tuple]] = None,
|
|
343
|
+
json: Optional[Dict[str, Any]] = None,
|
|
344
|
+
) -> Response:
|
|
345
|
+
"""
|
|
346
|
+
重写 request 方法,添加认证信息和统计上报
|
|
347
|
+
"""
|
|
348
|
+
# 初始化 headers
|
|
349
|
+
if headers is None:
|
|
350
|
+
headers = {}
|
|
351
|
+
else:
|
|
352
|
+
headers = headers.copy()
|
|
223
353
|
|
|
224
|
-
#
|
|
225
|
-
|
|
226
|
-
'query_params': params or {},
|
|
227
|
-
'headers': headers
|
|
228
|
-
}
|
|
354
|
+
# 从 request_context 获取认证信息
|
|
355
|
+
request_context = get_request_context()
|
|
229
356
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
357
|
+
if request_context:
|
|
358
|
+
# 添加应用ID
|
|
359
|
+
app_id = request_context.get('app_id')
|
|
360
|
+
if app_id is not None:
|
|
361
|
+
headers['X-App-ID'] = str(app_id)
|
|
362
|
+
|
|
363
|
+
# 添加应用密钥
|
|
364
|
+
app_secret = request_context.get('app_secret')
|
|
365
|
+
if app_secret:
|
|
366
|
+
headers['X-App-Secret'] = app_secret
|
|
367
|
+
|
|
368
|
+
# 添加认证令牌
|
|
369
|
+
token = request_context.get('token')
|
|
370
|
+
if token:
|
|
371
|
+
headers['Authorization'] = f'Bearer {token}'
|
|
372
|
+
|
|
373
|
+
# 添加客户端IP
|
|
374
|
+
ip_address = request_context.get('ip_address')
|
|
375
|
+
if ip_address:
|
|
376
|
+
headers['x-real-ip'] = ip_address
|
|
377
|
+
|
|
378
|
+
# 添加 User Agent
|
|
379
|
+
user_agent = request_context.get('user_agent')
|
|
380
|
+
if user_agent:
|
|
381
|
+
headers['user-agent'] = user_agent
|
|
382
|
+
|
|
383
|
+
# 添加追踪ID
|
|
384
|
+
trace_id = request_context.get('trace_id')
|
|
385
|
+
if trace_id:
|
|
386
|
+
headers['X-Trace-ID'] = trace_id
|
|
235
387
|
|
|
236
|
-
#
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
status_code=status_code,
|
|
241
|
-
response_time=response_time,
|
|
242
|
-
token=token,
|
|
243
|
-
error_message=error_message,
|
|
244
|
-
request_params=request_params
|
|
245
|
-
)
|
|
388
|
+
# 记录开始时间
|
|
389
|
+
start_time = time.time()
|
|
390
|
+
response = None
|
|
391
|
+
error_message = None
|
|
246
392
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
393
|
+
try:
|
|
394
|
+
# 调用父类的 request 方法
|
|
395
|
+
logger.info(f"AuthSession 发起请求: {method} {url} with headers={headers}")
|
|
396
|
+
response = super().request(
|
|
397
|
+
method=method,
|
|
398
|
+
url=url,
|
|
399
|
+
params=params,
|
|
400
|
+
data=data,
|
|
401
|
+
headers=headers,
|
|
402
|
+
cookies=cookies,
|
|
403
|
+
files=files,
|
|
404
|
+
auth=auth,
|
|
405
|
+
timeout=timeout,
|
|
406
|
+
allow_redirects=allow_redirects,
|
|
407
|
+
proxies=proxies,
|
|
408
|
+
hooks=hooks,
|
|
409
|
+
stream=stream,
|
|
410
|
+
verify=verify,
|
|
411
|
+
cert=cert,
|
|
412
|
+
json=json,
|
|
413
|
+
)
|
|
414
|
+
logger.info(f"AuthSession 请求响应: {method} {url} 状态码: {response.status_code}")
|
|
415
|
+
return response
|
|
416
|
+
|
|
417
|
+
except Exception as e:
|
|
418
|
+
error_message = str(e)
|
|
419
|
+
logger.error(f"AuthSession 请求失败: {method} {url} 错误: {error_message}")
|
|
420
|
+
raise
|
|
421
|
+
|
|
422
|
+
finally:
|
|
423
|
+
# 计算响应时间
|
|
424
|
+
response_time = time.time() - start_time
|
|
425
|
+
|
|
426
|
+
# 上报统计信息
|
|
427
|
+
_report_stats(
|
|
428
|
+
url=url,
|
|
429
|
+
method=method,
|
|
430
|
+
response=response,
|
|
431
|
+
response_time=response_time,
|
|
432
|
+
error_message=error_message,
|
|
433
|
+
request_context=request_context,
|
|
434
|
+
headers=headers,
|
|
435
|
+
params=params,
|
|
436
|
+
json_data=json,
|
|
437
|
+
form_data=data
|
|
438
|
+
)
|
|
250
439
|
|
|
251
440
|
|
|
252
441
|
# ============ HTTPX 异步请求封装 ============
|
|
@@ -387,7 +576,50 @@ if HTTPX_AVAILABLE:
|
|
|
387
576
|
form_data=data
|
|
388
577
|
)
|
|
389
578
|
|
|
579
|
+
async def async_auth_httpx_request_get(
|
|
580
|
+
url: str,
|
|
581
|
+
params: Optional[Dict[str, Any]] = None,
|
|
582
|
+
headers: Optional[Dict[str, str]] = None,
|
|
583
|
+
**kwargs
|
|
584
|
+
) -> httpx.Response:
|
|
585
|
+
"""
|
|
586
|
+
异步 GET 请求快捷方法
|
|
587
|
+
|
|
588
|
+
Args:
|
|
589
|
+
url: 请求 URL
|
|
590
|
+
params: URL 查询参数
|
|
591
|
+
headers: 请求头
|
|
592
|
+
**kwargs: 其他 async_auth_httpx_request 支持的参数
|
|
593
|
+
|
|
594
|
+
Returns:
|
|
595
|
+
httpx.Response: 响应对象
|
|
596
|
+
"""
|
|
597
|
+
return await async_auth_httpx_request('GET', url, params=params, headers=headers, **kwargs)
|
|
390
598
|
|
|
599
|
+
async def async_auth_httpx_request_post(
|
|
600
|
+
url: str,
|
|
601
|
+
data: Optional[Union[Dict[str, Any], str, bytes]] = None,
|
|
602
|
+
json: Optional[Dict[str, Any]] = None,
|
|
603
|
+
params: Optional[Dict[str, Any]] = None,
|
|
604
|
+
headers: Optional[Dict[str, str]] = None,
|
|
605
|
+
**kwargs
|
|
606
|
+
) -> httpx.Response:
|
|
607
|
+
"""
|
|
608
|
+
异步 POST 请求快捷方法
|
|
609
|
+
|
|
610
|
+
Args:
|
|
611
|
+
url: 请求 URL
|
|
612
|
+
data: 请求体数据 (form-data 或 raw)
|
|
613
|
+
json: JSON 请求体数据
|
|
614
|
+
params: URL 查询参数
|
|
615
|
+
headers: 请求头
|
|
616
|
+
**kwargs: 其他 async_auth_httpx_request 支持的参数
|
|
617
|
+
|
|
618
|
+
Returns:
|
|
619
|
+
httpx.Response: 响应对象
|
|
620
|
+
"""
|
|
621
|
+
return await async_auth_httpx_request('POST', url, data=data, json=json, params=params, headers=headers, **kwargs)
|
|
622
|
+
|
|
391
623
|
class AsyncAuthClient:
|
|
392
624
|
"""
|
|
393
625
|
异步认证客户端(httpx.AsyncClient 包装)
|
|
@@ -591,7 +823,51 @@ if HTTPX_AVAILABLE:
|
|
|
591
823
|
print(response.json())
|
|
592
824
|
|
|
593
825
|
|
|
594
|
-
2.
|
|
826
|
+
2. 使用 AuthSession(支持连接池,推荐):
|
|
827
|
+
|
|
828
|
+
from huace_aigc_auth_client.auth_request import AuthSession
|
|
829
|
+
from huace_aigc_auth_client.user_context import set_request_context
|
|
830
|
+
|
|
831
|
+
# 设置请求上下文
|
|
832
|
+
set_request_context(
|
|
833
|
+
app_id='your-app-id',
|
|
834
|
+
app_secret='your-app-secret',
|
|
835
|
+
token='user-access-token'
|
|
836
|
+
)
|
|
837
|
+
|
|
838
|
+
# 使用 AuthSession(自动启用连接池)
|
|
839
|
+
with AuthSession() as session:
|
|
840
|
+
# GET 请求
|
|
841
|
+
response = session.get('https://api.example.com/users', params={'page': 1})
|
|
842
|
+
print(response.json())
|
|
843
|
+
|
|
844
|
+
# POST 请求
|
|
845
|
+
response = session.post(
|
|
846
|
+
'https://api.example.com/users',
|
|
847
|
+
json={'name': 'John', 'email': 'john@example.com'}
|
|
848
|
+
)
|
|
849
|
+
print(response.json())
|
|
850
|
+
|
|
851
|
+
# 多个请求复用同一个连接池,性能更好
|
|
852
|
+
for i in range(10):
|
|
853
|
+
response = session.get(f'https://api.example.com/items/{i}')
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
3. 不使用上下文管理器的 AuthSession:
|
|
857
|
+
|
|
858
|
+
from huace_aigc_auth_client.auth_request import AuthSession
|
|
859
|
+
|
|
860
|
+
# 创建 Session
|
|
861
|
+
session = AuthSession()
|
|
862
|
+
|
|
863
|
+
try:
|
|
864
|
+
response = session.get('https://api.example.com/users')
|
|
865
|
+
print(response.json())
|
|
866
|
+
finally:
|
|
867
|
+
session.close() # 手动关闭
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
4. 带参数的请求:
|
|
595
871
|
|
|
596
872
|
# GET 请求带查询参数
|
|
597
873
|
response = auth_request(
|
|
@@ -615,7 +891,7 @@ if HTTPX_AVAILABLE:
|
|
|
615
891
|
)
|
|
616
892
|
|
|
617
893
|
|
|
618
|
-
|
|
894
|
+
5. 覆盖默认 headers:
|
|
619
895
|
|
|
620
896
|
# 可以手动指定 headers,会与自动添加的 headers 合并
|
|
621
897
|
response = auth_request(
|
{huace_aigc_auth_client-1.1.33.dist-info → huace_aigc_auth_client-1.1.35.dist-info}/METADATA
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: huace-aigc-auth-client
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.35
|
|
4
4
|
Summary: 华策AIGC Auth Client - 提供 Token 验证、用户信息获取、权限检查、旧系统接入等功能
|
|
5
5
|
Author-email: Huace <support@huace.com>
|
|
6
6
|
License: MIT
|
|
@@ -691,6 +691,329 @@ sync_config = create_sync_config(
|
|
|
691
691
|
|
|
692
692
|
---
|
|
693
693
|
|
|
694
|
+
## 高级功能
|
|
695
|
+
|
|
696
|
+
### API 统计收集
|
|
697
|
+
|
|
698
|
+
SDK 提供了接口统计收集功能,自动收集和上报 API 调用数据到鉴权中心。
|
|
699
|
+
|
|
700
|
+
#### 1. 初始化统计收集器
|
|
701
|
+
|
|
702
|
+
```python
|
|
703
|
+
from huace_aigc_auth_client import init_api_stats_collector
|
|
704
|
+
|
|
705
|
+
# 仅仅示例,SDK 接入鉴权会默认启用数据收集功能(可以手动传参关闭)
|
|
706
|
+
# 在应用启动时初始化
|
|
707
|
+
init_api_stats_collector(
|
|
708
|
+
api_url='http://auth.example.com/api/sdk',
|
|
709
|
+
app_id='your-app-id',
|
|
710
|
+
app_secret='your-app-secret',
|
|
711
|
+
batch_size=10, # 批量提交大小
|
|
712
|
+
flush_interval=5.0, # 刷新间隔(秒)
|
|
713
|
+
enabled=True # 是否启用
|
|
714
|
+
)
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
#### 2. 在中间件中自动收集
|
|
718
|
+
|
|
719
|
+
**FastAPI 示例:**
|
|
720
|
+
|
|
721
|
+
```python
|
|
722
|
+
from fastapi import FastAPI, Request
|
|
723
|
+
from huace_aigc_auth_client import collect_api_stat
|
|
724
|
+
import time
|
|
725
|
+
|
|
726
|
+
app = FastAPI()
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
# 仅仅示例,SDK 内默认会启用数据收集未 exclude 的接口(可以手动传参关闭)
|
|
730
|
+
@app.middleware("http")
|
|
731
|
+
async def monitor_middleware(request: Request, call_next):
|
|
732
|
+
start_time = time.time()
|
|
733
|
+
|
|
734
|
+
try:
|
|
735
|
+
response = await call_next(request)
|
|
736
|
+
response_time = time.time() - start_time
|
|
737
|
+
|
|
738
|
+
# 从请求上下文获取 token
|
|
739
|
+
token = request.state.user_info.token if hasattr(request.state, 'user_info') else None
|
|
740
|
+
|
|
741
|
+
# 收集统计(会自动过滤 3xx 重定向请求)
|
|
742
|
+
collect_api_stat(
|
|
743
|
+
api_path=request.url.path,
|
|
744
|
+
api_method=request.method,
|
|
745
|
+
status_code=response.status_code,
|
|
746
|
+
response_time=response_time,
|
|
747
|
+
token=token,
|
|
748
|
+
request_params={
|
|
749
|
+
'headers': dict(request.headers),
|
|
750
|
+
'query_params': dict(request.query_params)
|
|
751
|
+
}
|
|
752
|
+
)
|
|
753
|
+
|
|
754
|
+
return response
|
|
755
|
+
except Exception as e:
|
|
756
|
+
response_time = time.time() - start_time
|
|
757
|
+
collect_api_stat(
|
|
758
|
+
api_path=request.url.path,
|
|
759
|
+
api_method=request.method,
|
|
760
|
+
status_code=500,
|
|
761
|
+
response_time=response_time,
|
|
762
|
+
token=token,
|
|
763
|
+
error_message=str(e)
|
|
764
|
+
)
|
|
765
|
+
raise
|
|
766
|
+
|
|
767
|
+
@app.on_event("shutdown")
|
|
768
|
+
async def shutdown_event():
|
|
769
|
+
from huace_aigc_auth_client import stop_api_stats_collector
|
|
770
|
+
stop_api_stats_collector()
|
|
771
|
+
```
|
|
772
|
+
|
|
773
|
+
**特性说明:**
|
|
774
|
+
- 异步队列收集,不阻塞主流程
|
|
775
|
+
- 批量提交,减少网络开销
|
|
776
|
+
- 自动过滤 3xx 重定向请求
|
|
777
|
+
- 按 token 分组提交
|
|
778
|
+
- 静默失败,不影响主业务
|
|
779
|
+
|
|
780
|
+
---
|
|
781
|
+
|
|
782
|
+
### 认证请求封装
|
|
783
|
+
|
|
784
|
+
SDK 提供了 `auth_request` 函数,封装标准的 HTTP 请求,自动添加认证信息并上报统计。
|
|
785
|
+
|
|
786
|
+
#### 1. 基本使用
|
|
787
|
+
|
|
788
|
+
```python
|
|
789
|
+
from huace_aigc_auth_client import auth_request, set_request_context
|
|
790
|
+
|
|
791
|
+
# 设置请求上下文(通常在中间件中完成)
|
|
792
|
+
set_request_context(
|
|
793
|
+
app_id='your-app-id',
|
|
794
|
+
app_secret='your-app-secret',
|
|
795
|
+
token='user-access-token',
|
|
796
|
+
ip_address='192.168.1.1',
|
|
797
|
+
user_agent='Mozilla/5.0...',
|
|
798
|
+
trace_id='trace-123'
|
|
799
|
+
)
|
|
800
|
+
|
|
801
|
+
# 发起请求(会自动添加认证信息)
|
|
802
|
+
response = auth_request('GET', 'https://api.example.com/data')
|
|
803
|
+
print(response.json())
|
|
804
|
+
```
|
|
805
|
+
|
|
806
|
+
#### 2. 带参数的请求
|
|
807
|
+
|
|
808
|
+
```python
|
|
809
|
+
# GET 请求带查询参数
|
|
810
|
+
response = auth_request(
|
|
811
|
+
'GET',
|
|
812
|
+
'https://api.example.com/users',
|
|
813
|
+
params={'page': 1, 'size': 10}
|
|
814
|
+
)
|
|
815
|
+
|
|
816
|
+
# POST 请求带 JSON 数据
|
|
817
|
+
response = auth_request(
|
|
818
|
+
'POST',
|
|
819
|
+
'https://api.example.com/users',
|
|
820
|
+
json={'name': 'John', 'email': 'john@example.com'}
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
# POST 请求带表单数据
|
|
824
|
+
response = auth_request(
|
|
825
|
+
'POST',
|
|
826
|
+
'https://api.example.com/upload',
|
|
827
|
+
data={'field1': 'value1', 'field2': 'value2'}
|
|
828
|
+
)
|
|
829
|
+
```
|
|
830
|
+
|
|
831
|
+
#### 3. 异步请求(httpx)
|
|
832
|
+
|
|
833
|
+
需要安装 httpx:`pip install httpx`
|
|
834
|
+
|
|
835
|
+
```python
|
|
836
|
+
from huace_aigc_auth_client import async_auth_httpx_request, AsyncAuthClient
|
|
837
|
+
import asyncio
|
|
838
|
+
|
|
839
|
+
# 方式1:使用函数
|
|
840
|
+
async def example1():
|
|
841
|
+
response = await async_auth_httpx_request('GET', 'https://api.example.com/data')
|
|
842
|
+
print(response.json())
|
|
843
|
+
|
|
844
|
+
# 方式2:使用 AsyncAuthClient(推荐用于多个请求)
|
|
845
|
+
async def example2():
|
|
846
|
+
async with AsyncAuthClient(timeout=10.0) as client:
|
|
847
|
+
# POST 请求
|
|
848
|
+
response = await client.post(
|
|
849
|
+
'https://api.example.com/users',
|
|
850
|
+
json={'name': 'John'}
|
|
851
|
+
)
|
|
852
|
+
|
|
853
|
+
# GET 请求
|
|
854
|
+
response = await client.get(
|
|
855
|
+
'https://api.example.com/users',
|
|
856
|
+
params={'page': 1}
|
|
857
|
+
)
|
|
858
|
+
|
|
859
|
+
asyncio.run(example1())
|
|
860
|
+
```
|
|
861
|
+
|
|
862
|
+
**自动添加的请求头:**
|
|
863
|
+
- `X-App-ID`: 应用ID
|
|
864
|
+
- `X-App-Secret`: 应用密钥
|
|
865
|
+
- `Authorization`: Bearer token
|
|
866
|
+
- `x-real-ip`: 客户端真实IP
|
|
867
|
+
- `user-agent`: User Agent
|
|
868
|
+
- `X-Trace-ID`: 追踪ID
|
|
869
|
+
|
|
870
|
+
---
|
|
871
|
+
|
|
872
|
+
### 用户上下文管理
|
|
873
|
+
|
|
874
|
+
SDK 提供了完整的用户上下文管理功能,支持同步和异步环境。
|
|
875
|
+
|
|
876
|
+
#### 1. 设置和获取用户信息
|
|
877
|
+
|
|
878
|
+
```python
|
|
879
|
+
from huace_aigc_auth_client import (
|
|
880
|
+
set_current_user,
|
|
881
|
+
get_current_user,
|
|
882
|
+
get_current_user_id,
|
|
883
|
+
get_current_username,
|
|
884
|
+
is_current_user_admin
|
|
885
|
+
)
|
|
886
|
+
|
|
887
|
+
# 在中间件中设置
|
|
888
|
+
set_current_user({
|
|
889
|
+
'user_id': 123,
|
|
890
|
+
'username': 'john',
|
|
891
|
+
'app_id': 1,
|
|
892
|
+
'app_code': 'myapp',
|
|
893
|
+
'token': 'xxx',
|
|
894
|
+
'roles': ['admin'],
|
|
895
|
+
'permissions': ['user:read', 'user:write'],
|
|
896
|
+
'is_admin': True
|
|
897
|
+
})
|
|
898
|
+
|
|
899
|
+
# 在业务代码中获取
|
|
900
|
+
def some_business_logic():
|
|
901
|
+
user = get_current_user()
|
|
902
|
+
user_id = get_current_user_id()
|
|
903
|
+
username = get_current_username()
|
|
904
|
+
|
|
905
|
+
if user:
|
|
906
|
+
print(f"当前用户: {username} ({user_id})")
|
|
907
|
+
|
|
908
|
+
if is_current_user_admin():
|
|
909
|
+
print("当前用户是管理员")
|
|
910
|
+
```
|
|
911
|
+
|
|
912
|
+
#### 2. 请求上下文管理
|
|
913
|
+
|
|
914
|
+
```python
|
|
915
|
+
from huace_aigc_auth_client import (
|
|
916
|
+
set_request_context,
|
|
917
|
+
get_request_context,
|
|
918
|
+
get_client_ip,
|
|
919
|
+
get_user_agent,
|
|
920
|
+
get_trace_id
|
|
921
|
+
)
|
|
922
|
+
|
|
923
|
+
# 设置请求上下文
|
|
924
|
+
set_request_context(
|
|
925
|
+
ip_address='192.168.1.1',
|
|
926
|
+
user_agent='Mozilla/5.0...',
|
|
927
|
+
trace_id='trace-123',
|
|
928
|
+
app_id='your-app-id',
|
|
929
|
+
app_secret='your-app-secret',
|
|
930
|
+
token='user-token'
|
|
931
|
+
)
|
|
932
|
+
|
|
933
|
+
# 获取请求上下文信息
|
|
934
|
+
ctx = get_request_context()
|
|
935
|
+
ip = get_client_ip()
|
|
936
|
+
ua = get_user_agent()
|
|
937
|
+
trace = get_trace_id()
|
|
938
|
+
```
|
|
939
|
+
|
|
940
|
+
#### 3. 在 FastAPI 中集成
|
|
941
|
+
|
|
942
|
+
```python
|
|
943
|
+
from fastapi import FastAPI, Request, Depends
|
|
944
|
+
from huace_aigc_auth_client import (
|
|
945
|
+
set_current_user,
|
|
946
|
+
set_request_context,
|
|
947
|
+
get_current_user,
|
|
948
|
+
clear_current_user,
|
|
949
|
+
clear_request_context
|
|
950
|
+
)
|
|
951
|
+
|
|
952
|
+
app = FastAPI()
|
|
953
|
+
|
|
954
|
+
@app.middleware("http")
|
|
955
|
+
async def user_context_middleware(request: Request, call_next):
|
|
956
|
+
# 从认证中获取用户信息
|
|
957
|
+
user_info = request.state.user_info if hasattr(request.state, 'user_info') else None
|
|
958
|
+
|
|
959
|
+
if user_info:
|
|
960
|
+
# 设置用户上下文
|
|
961
|
+
set_current_user({
|
|
962
|
+
'user_id': user_info.id,
|
|
963
|
+
'username': user_info.username,
|
|
964
|
+
'app_id': getattr(user_info, 'app_id', None),
|
|
965
|
+
'is_admin': user_info.is_admin
|
|
966
|
+
})
|
|
967
|
+
|
|
968
|
+
# 设置请求上下文
|
|
969
|
+
set_request_context(
|
|
970
|
+
ip_address=request.client.host,
|
|
971
|
+
user_agent=request.headers.get('user-agent'),
|
|
972
|
+
trace_id=request.headers.get('x-trace-id'),
|
|
973
|
+
token=request.headers.get('authorization', '').replace('Bearer ', '')
|
|
974
|
+
)
|
|
975
|
+
|
|
976
|
+
try:
|
|
977
|
+
response = await call_next(request)
|
|
978
|
+
return response
|
|
979
|
+
finally:
|
|
980
|
+
clear_current_user()
|
|
981
|
+
clear_request_context()
|
|
982
|
+
|
|
983
|
+
# 在任意地方使用
|
|
984
|
+
def my_service_function():
|
|
985
|
+
user = get_current_user()
|
|
986
|
+
if user:
|
|
987
|
+
print(f"执行操作的用户: {user['username']}")
|
|
988
|
+
```
|
|
989
|
+
|
|
990
|
+
#### 4. 装饰器中使用
|
|
991
|
+
|
|
992
|
+
```python
|
|
993
|
+
from functools import wraps
|
|
994
|
+
from huace_aigc_auth_client import is_current_user_admin
|
|
995
|
+
|
|
996
|
+
def require_admin(func):
|
|
997
|
+
@wraps(func)
|
|
998
|
+
async def wrapper(*args, **kwargs):
|
|
999
|
+
if not is_current_user_admin():
|
|
1000
|
+
raise HTTPException(status_code=403, detail="需要管理员权限")
|
|
1001
|
+
return await func(*args, **kwargs)
|
|
1002
|
+
return wrapper
|
|
1003
|
+
|
|
1004
|
+
@require_admin
|
|
1005
|
+
async def admin_endpoint():
|
|
1006
|
+
return {"message": "管理员操作"}
|
|
1007
|
+
```
|
|
1008
|
+
|
|
1009
|
+
**特性说明:**
|
|
1010
|
+
- 使用 `threading.local()` 和 `contextvars.ContextVar` 实现
|
|
1011
|
+
- 同时支持同步和异步环境
|
|
1012
|
+
- 线程安全和异步任务隔离
|
|
1013
|
+
- 无需层层传递参数
|
|
1014
|
+
|
|
1015
|
+
---
|
|
1016
|
+
|
|
694
1017
|
## 导出清单
|
|
695
1018
|
|
|
696
1019
|
```python
|
|
@@ -720,6 +1043,36 @@ from huace_aigc_auth_client import (
|
|
|
720
1043
|
# Webhook 接收
|
|
721
1044
|
register_webhook_router,
|
|
722
1045
|
verify_webhook_signature,
|
|
1046
|
+
|
|
1047
|
+
# API 统计收集
|
|
1048
|
+
ApiStatsCollector,
|
|
1049
|
+
init_api_stats_collector,
|
|
1050
|
+
get_api_stats_collector,
|
|
1051
|
+
stop_api_stats_collector,
|
|
1052
|
+
collect_api_stat,
|
|
1053
|
+
|
|
1054
|
+
# 认证请求封装
|
|
1055
|
+
auth_request,
|
|
1056
|
+
async_auth_httpx_request,
|
|
1057
|
+
AsyncAuthClient,
|
|
1058
|
+
|
|
1059
|
+
# 用户上下文管理
|
|
1060
|
+
set_current_user,
|
|
1061
|
+
get_current_user,
|
|
1062
|
+
get_current_user_id,
|
|
1063
|
+
get_current_username,
|
|
1064
|
+
get_current_app_id,
|
|
1065
|
+
get_current_app_code,
|
|
1066
|
+
is_current_user_admin,
|
|
1067
|
+
clear_current_user,
|
|
1068
|
+
set_request_context,
|
|
1069
|
+
get_request_context,
|
|
1070
|
+
get_client_ip,
|
|
1071
|
+
get_user_agent,
|
|
1072
|
+
get_request_id,
|
|
1073
|
+
get_trace_id,
|
|
1074
|
+
get_request_token,
|
|
1075
|
+
clear_request_context,
|
|
723
1076
|
)
|
|
724
1077
|
```
|
|
725
1078
|
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
huace_aigc_auth_client/__init__.py,sha256=
|
|
1
|
+
huace_aigc_auth_client/__init__.py,sha256=d1YC-9M_saTbdMEaMvDtzT-gDHc5wep2667pZsCKrag,6337
|
|
2
2
|
huace_aigc_auth_client/api_stats_collector.py,sha256=ADpjpHXMqn80YI4UltWHbzAO_szykU9ZCvwXgBRWFIM,11046
|
|
3
|
-
huace_aigc_auth_client/auth_request.py,sha256=
|
|
3
|
+
huace_aigc_auth_client/auth_request.py,sha256=Xlg1hq5jgXv5gUhOeh2ks0GtE05d4D9lrGZigxfB1o0,31486
|
|
4
4
|
huace_aigc_auth_client/legacy_adapter.py,sha256=TVCBAKejE2z2HQFsEwDW8LMiaIkXNfz3Mxv6_E-UJFY,24102
|
|
5
5
|
huace_aigc_auth_client/sdk.py,sha256=rproo913OAi37wz_rMYgxzP3F1YyY3nc5e35JS5WvoY,37751
|
|
6
6
|
huace_aigc_auth_client/user_context.py,sha256=IqdX6Xd2jJwvij6Hc2qWAFWj5pn3wHqk0RBsaXKLP8g,6795
|
|
7
7
|
huace_aigc_auth_client/webhook.py,sha256=XQZYEbMoqIdqZWCGSTcedeDKJpDbUVSq5g08g-6Qucg,4124
|
|
8
8
|
huace_aigc_auth_client/webhook_flask.py,sha256=Iosu4dBtRhQZM_ytn-bn82MpVsyOiV28FBnt7Tfh31U,7225
|
|
9
|
-
huace_aigc_auth_client-1.1.
|
|
10
|
-
huace_aigc_auth_client-1.1.
|
|
11
|
-
huace_aigc_auth_client-1.1.
|
|
12
|
-
huace_aigc_auth_client-1.1.
|
|
13
|
-
huace_aigc_auth_client-1.1.
|
|
9
|
+
huace_aigc_auth_client-1.1.35.dist-info/licenses/LICENSE,sha256=z7dgC7KljhBLNvKjN15391nMj3aLt0gbud8-Yf1F8EQ,1063
|
|
10
|
+
huace_aigc_auth_client-1.1.35.dist-info/METADATA,sha256=5eRkyxueBTCBuqUI-IAx22mcnL8-_eOe_mnaZuC09ZE,32415
|
|
11
|
+
huace_aigc_auth_client-1.1.35.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
|
|
12
|
+
huace_aigc_auth_client-1.1.35.dist-info/top_level.txt,sha256=kbv0nQ6PQ0JVneWPH7O2AbtlJnP7AjvFJ6JjM6ZEBxo,23
|
|
13
|
+
huace_aigc_auth_client-1.1.35.dist-info/RECORD,,
|
|
File without changes
|
{huace_aigc_auth_client-1.1.33.dist-info → huace_aigc_auth_client-1.1.35.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|
{huace_aigc_auth_client-1.1.33.dist-info → huace_aigc_auth_client-1.1.35.dist-info}/top_level.txt
RENAMED
|
File without changes
|