ReMe/reme_cli/component/client/http_client.py
jinli.yl b9ce64de7f refactor(component): restructure client and component architecture
- Replace ReMeClient with modular client implementations
- Add component registry with type-based registration system
- Introduce BaseClient extending BaseComponent with lifecycle management
- Create HttpClient with environment-based service discovery
- Add constants for default host/port configurations
- Update service info propagation through environment variables
- Restructure imports and exports across component modules
- Add run_coro_safely utility for safe coroutine execution
- Implement component type enumeration for better organization
- Register components with R decorator for automatic discovery
- Add placeholder methods for ReMe core functionalities
- Update command-line entry point to use dynamic client selection
2026-04-14 15:51:07 +08:00

61 lines
1.7 KiB
Python

"""HTTP client for ReMe services."""
import json
import os
from typing import Any
import httpx
from .base_client import BaseClient
from ..component_registry import R
from ...constants import REME_SERVICE_INFO, REME_DEFAULT_HOST, REME_DEFAULT_PORT
@R.register("http")
class HttpClient(BaseClient):
"""HTTP client for ReMe service."""
def __init__(
self,
action: str,
host: str | None = None,
port: int | None = None,
timeout: float = 30.0,
**kwargs
):
super().__init__(**kwargs)
if host and port:
pass
elif service_info := os.environ.get(REME_SERVICE_INFO):
try:
data = json.loads(service_info)
host = data.get("host", host)
port = data.get("port", port)
except Exception:
pass
else:
host = REME_DEFAULT_HOST
port = REME_DEFAULT_PORT
self.action = action
self.base_url = f"http://{host}:{port}"
self.timeout = timeout
async def _start(self, app_context=None) -> None:
"""Initialize the HTTP client."""
if self.client is None:
self.client = httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
)
async def __call__(self, **_kwargs) -> dict:
response = await self.client.post(f"/{self.action}", json=self.kwargs)
response.raise_for_status()
return response.json()
async def _close(self) -> None:
if self.client is not None:
await self.client.aclose()
self.client = None