77 lines
3.2 KiB
Python
77 lines
3.2 KiB
Python
import os
|
|
import requests
|
|
import time
|
|
from typing import Dict, Any, Optional
|
|
from .exceptions import AEAPIError, AEAuthError, AERateLimitError, AEBadRequestError, AENotFoundError
|
|
|
|
class AEClient:
|
|
"""Base client for interacting with AE Platform API."""
|
|
|
|
BASE_URL = "https://api2.aeplatform.ru/api/v1"
|
|
|
|
def __init__(self, api_token: Optional[str] = None, user_id: Optional[str] = None):
|
|
# Fetch from env if not provided
|
|
self.api_token = api_token or os.getenv('AE_API_TOKEN')
|
|
self.user_id = user_id or os.getenv('AE_USER_ID')
|
|
|
|
if not self.api_token:
|
|
raise ValueError("AE_API_TOKEN must be provided")
|
|
|
|
self.session = requests.Session()
|
|
# AE Platform API requires JWT token and locale
|
|
self.session.headers.update({
|
|
"Authorization": self.api_token, # Token from documentation is passed directly in Authorization header
|
|
"x-request-locale": "ru_RU",
|
|
"Content-Type": "application/json"
|
|
})
|
|
|
|
def request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, retries: int = 3) -> Dict[str, Any]:
|
|
"""Perform HTTP request to AE Platform API with automatic retries."""
|
|
url = f"{self.BASE_URL}{path}"
|
|
|
|
for attempt in range(retries):
|
|
try:
|
|
response = self.session.request(method, url, json=data, params=params)
|
|
|
|
# Check rate limiting
|
|
if response.status_code == 429:
|
|
if attempt < retries - 1:
|
|
time.sleep(2 ** attempt) # Exponential backoff
|
|
continue
|
|
raise AERateLimitError("Rate limit exceeded")
|
|
|
|
if response.status_code in (401, 403):
|
|
raise AEAuthError(f"Authentication failed: {response.text}")
|
|
|
|
if response.status_code in (400, 422):
|
|
raise AEBadRequestError(f"Bad Request / Unprocessable Entity: {response.text}")
|
|
|
|
if response.status_code == 404:
|
|
raise AENotFoundError(f"Not Found: {response.text}")
|
|
|
|
response.raise_for_status()
|
|
|
|
if response.content:
|
|
try:
|
|
return response.json()
|
|
except ValueError:
|
|
return {"status": "success", "text": response.text}
|
|
return {}
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
if attempt < retries - 1:
|
|
time.sleep(2 ** attempt)
|
|
continue
|
|
raise AEAPIError(f"Request failed: {str(e)}")
|
|
|
|
raise AEAPIError("Request failed after max retries")
|
|
|
|
def post(self, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
return self.request("POST", path, data=data)
|
|
|
|
def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
return self.request("GET", path, params=params)
|
|
|
|
def put(self, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
return self.request("PUT", path, data=data)
|