feat: migrate exchange and monitor CLI commands to use centralized aitbc package HTTP client
Some checks failed
CLI Tests / test-cli (push) Failing after 2s
Security Scanning / security-scan (push) Successful in 23s

- Replace httpx.Client with aitbc.AITBCHTTPClient in exchange.py list_pairs command
- Migrate monitor.py from httpx to aitbc.AITBCHTTPClient across all commands
- Add aitbc imports: get_logger, AITBCHTTPClient, NetworkError to monitor.py
- Remove httpx import from monitor.py
- Fix indentation in list_pairs command
- Add NetworkError exception handling in list_pairs
- Remove async context managers in favor
This commit is contained in:
aitbc
2026-04-24 23:55:06 +02:00
parent f912fa131d
commit ca07a1c670
2 changed files with 31 additions and 33 deletions

View File

@@ -649,20 +649,13 @@ def list_pairs(ctx, pair: Optional[str], exchange: Optional[str], status: Option
try: try:
http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10) http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
response = http_client.get( pairs = http_client.get("/exchange/pairs", params=params)
f"{config.coordinator_url}/v1/exchange/pairs", success("Trading pairs:")
params=params, output(pairs, ctx.obj['output_format'])
timeout=10 except NetworkError as e:
)
if response.status_code == 200:
pairs = response.json()
success("Trading pairs:")
output(pairs, ctx.obj['output_format'])
else:
error(f"Failed to list trading pairs: {response.status_code}")
except Exception as e:
error(f"Network error: {e}") error(f"Network error: {e}")
except Exception as e:
error(f"Error: {e}")
@exchange.command() @exchange.command()

View File

@@ -1,7 +1,6 @@
"""Monitoring and dashboard commands for AITBC CLI""" """Monitoring and dashboard commands for AITBC CLI"""
import click import click
import httpx
import json import json
import time import time
from pathlib import Path from pathlib import Path
@@ -9,6 +8,14 @@ from typing import Optional
from datetime import datetime, timedelta from datetime import datetime, timedelta
from ..utils import output, error, success, console from ..utils import output, error, success, console
# Import shared modules
from aitbc.aitbc_logging import get_logger
from aitbc.http_client import AITBCHTTPClient
from aitbc.exceptions import NetworkError
# Initialize logger
logger = get_logger(__name__)
@click.group() @click.group()
def monitor(): def monitor():
@@ -37,17 +44,15 @@ def dashboard(ctx, refresh: int, duration: int):
# Fetch system dashboard # Fetch system dashboard
try: try:
with httpx.Client(timeout=5) as client: http_client = AITBCHTTPClient(base_url=config.coordinator_url, timeout=5)
# Get dashboard data # Get dashboard data
try: try:
url = f"{config.coordinator_url}/api/v1/dashboard" url = "/api/v1/dashboard"
resp = client.get( dashboard = http_http_client.get(
url, url,
headers={"X-Api-Key": config.api_key or ""} headers={"X-Api-Key": config.api_key or ""}
) )
if resp.status_code == 200: console.print("[bold green]Dashboard Status:[/bold green] Online")
dashboard = resp.json()
console.print("[bold green]Dashboard Status:[/bold green] Online")
# Overall status # Overall status
overall_status = dashboard.get("overall_status", "unknown") overall_status = dashboard.get("overall_status", "unknown")
@@ -107,10 +112,10 @@ def metrics(ctx, period: str, export_path: Optional[str]):
} }
try: try:
with httpx.Client(timeout=10) as client: http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
# Coordinator metrics # Coordinator metrics
try: try:
resp = client.get( resp = http_client.get(
f"{config.coordinator_url}/status", f"{config.coordinator_url}/status",
headers={"X-Api-Key": config.api_key or ""} headers={"X-Api-Key": config.api_key or ""}
) )
@@ -124,7 +129,7 @@ def metrics(ctx, period: str, export_path: Optional[str]):
# Job metrics # Job metrics
try: try:
resp = client.get( resp = http_client.get(
f"{config.coordinator_url}/jobs", f"{config.coordinator_url}/jobs",
headers={"X-Api-Key": config.api_key or ""}, headers={"X-Api-Key": config.api_key or ""},
params={"limit": 100} params={"limit": 100}
@@ -143,7 +148,7 @@ def metrics(ctx, period: str, export_path: Optional[str]):
# Miner metrics # Miner metrics
try: try:
resp = client.get( resp = http_client.get(
f"{config.coordinator_url}/miners", f"{config.coordinator_url}/miners",
headers={"X-Api-Key": config.api_key or ""} headers={"X-Api-Key": config.api_key or ""}
) )
@@ -232,7 +237,7 @@ def alerts(ctx, action: str, name: Optional[str], alert_type: Optional[str],
return return
if alert.get("webhook"): if alert.get("webhook"):
try: try:
with httpx.Client(timeout=10) as client: http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
resp = client.post(alert["webhook"], json={ resp = client.post(alert["webhook"], json={
"alert": name, "alert": name,
"type": alert["type"], "type": alert["type"],
@@ -267,9 +272,9 @@ def history(ctx, period: str):
} }
try: try:
with httpx.Client(timeout=10) as client: http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
try: try:
resp = client.get( resp = http_client.get(
f"{config.coordinator_url}/jobs", f"{config.coordinator_url}/jobs",
headers={"X-Api-Key": config.api_key or ""}, headers={"X-Api-Key": config.api_key or ""},
params={"limit": 500} params={"limit": 500}
@@ -352,7 +357,7 @@ def webhooks(ctx, action: str, name: Optional[str], url: Optional[str], events:
error(f"Webhook '{name}' not found") error(f"Webhook '{name}' not found")
return return
try: try:
with httpx.Client(timeout=10) as client: http_client = AITBCHTTPClient(base_url="http://localhost:8001/api/v1", timeout=10)
resp = client.post(wh["url"], json={ resp = client.post(wh["url"], json={
"event": "test", "event": "test",
"source": "aitbc-cli", "source": "aitbc-cli",