84 lines
2.4 KiB
Python
84 lines
2.4 KiB
Python
"""HTTP客户端封装"""
|
|
import os
|
|
from typing import Optional, Any, Dict
|
|
import httpx
|
|
|
|
from .trace import get_trace_id
|
|
|
|
|
|
class PlatformHttpClient:
|
|
"""平台HTTP客户端
|
|
|
|
自动传递trace_id和API Key
|
|
|
|
使用示例:
|
|
client = PlatformHttpClient(base_url="https://api.example.com")
|
|
response = await client.get("/users/1")
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
base_url: Optional[str] = None,
|
|
api_key: Optional[str] = None,
|
|
timeout: float = 30.0
|
|
):
|
|
self.base_url = base_url or os.getenv("PLATFORM_URL", "")
|
|
self.api_key = api_key or os.getenv("PLATFORM_API_KEY", "")
|
|
self.timeout = timeout
|
|
|
|
def _get_headers(self, extra_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
|
"""获取请求头"""
|
|
headers = {}
|
|
|
|
# 添加trace_id
|
|
trace_id = get_trace_id()
|
|
if trace_id:
|
|
headers["X-Trace-ID"] = trace_id
|
|
|
|
# 添加API Key
|
|
if self.api_key:
|
|
headers["X-API-Key"] = self.api_key
|
|
|
|
# 合并额外header
|
|
if extra_headers:
|
|
headers.update(extra_headers)
|
|
|
|
return headers
|
|
|
|
async def request(
|
|
self,
|
|
method: str,
|
|
path: str,
|
|
**kwargs
|
|
) -> httpx.Response:
|
|
"""发送HTTP请求"""
|
|
headers = self._get_headers(kwargs.pop("headers", None))
|
|
|
|
async with httpx.AsyncClient(
|
|
base_url=self.base_url,
|
|
timeout=self.timeout
|
|
) as client:
|
|
response = await client.request(
|
|
method=method,
|
|
url=path,
|
|
headers=headers,
|
|
**kwargs
|
|
)
|
|
return response
|
|
|
|
async def get(self, path: str, **kwargs) -> httpx.Response:
|
|
"""GET请求"""
|
|
return await self.request("GET", path, **kwargs)
|
|
|
|
async def post(self, path: str, **kwargs) -> httpx.Response:
|
|
"""POST请求"""
|
|
return await self.request("POST", path, **kwargs)
|
|
|
|
async def put(self, path: str, **kwargs) -> httpx.Response:
|
|
"""PUT请求"""
|
|
return await self.request("PUT", path, **kwargs)
|
|
|
|
async def delete(self, path: str, **kwargs) -> httpx.Response:
|
|
"""DELETE请求"""
|
|
return await self.request("DELETE", path, **kwargs)
|