feat: implement backend API clients for multi-marketplace integration and frontend service layer
This commit is contained in:
15
backend/avito_api/__init__.py
Normal file
15
backend/avito_api/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from .client import AvitoClient
|
||||
from .services.items import ItemsService
|
||||
from .services.messenger import MessengerService
|
||||
|
||||
class AvitoAPI:
|
||||
"""
|
||||
Main entry point for Avito SDK.
|
||||
Instantiates all services with a shared client.
|
||||
"""
|
||||
def __init__(self, client_id: str = None, client_secret: str = None):
|
||||
self.client = AvitoClient(client_id, client_secret)
|
||||
|
||||
# Initialize services
|
||||
self.items = ItemsService(self.client)
|
||||
self.messenger = MessengerService(self.client)
|
||||
97
backend/avito_api/client.py
Normal file
97
backend/avito_api/client.py
Normal file
@@ -0,0 +1,97 @@
|
||||
import os
|
||||
import requests
|
||||
import time
|
||||
from typing import Dict, Any, Optional
|
||||
from .exceptions import AvitoAPIError, AvitoAuthError, AvitoRateLimitError, AvitoBadRequestError, AvitoNotFoundError
|
||||
|
||||
class AvitoClient:
|
||||
"""Base client for interacting with Avito API."""
|
||||
|
||||
BASE_URL = "https://api.avito.ru"
|
||||
|
||||
def __init__(self, client_id: Optional[str] = None, client_secret: Optional[str] = None):
|
||||
# Fetch from env if not provided
|
||||
self.client_id = client_id or os.getenv('AVITO_CLIENT_ID')
|
||||
self.client_secret = client_secret or os.getenv('AVITO_CLIENT_SECRET')
|
||||
|
||||
if not self.client_id or not self.client_secret:
|
||||
raise ValueError("AVITO_CLIENT_ID and AVITO_CLIENT_SECRET must be provided")
|
||||
|
||||
self.session = requests.Session()
|
||||
self.access_token = None
|
||||
|
||||
# Получаем токен сразу при инициализации
|
||||
self._authenticate()
|
||||
|
||||
def _authenticate(self):
|
||||
"""Exchange Client ID and Secret for a temporary OAuth access token."""
|
||||
url = f"{self.BASE_URL}/token/"
|
||||
data = {
|
||||
"client_id": self.client_id,
|
||||
"client_secret": self.client_secret,
|
||||
"grant_type": "client_credentials"
|
||||
}
|
||||
|
||||
response = requests.post(url, data=data)
|
||||
if response.status_code != 200:
|
||||
raise AvitoAuthError(f"Failed to get Avito token: {response.text}")
|
||||
|
||||
token_data = response.json()
|
||||
self.access_token = token_data.get("access_token")
|
||||
|
||||
self.session.headers.update({
|
||||
"Authorization": f"Bearer {self.access_token}",
|
||||
"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 Avito API with automatic retries and token refresh."""
|
||||
url = f"{self.BASE_URL}{path}"
|
||||
|
||||
for attempt in range(retries):
|
||||
try:
|
||||
response = self.session.request(method, url, json=data, params=params)
|
||||
|
||||
# Check for expired token (401) or Forbidden (403)
|
||||
if response.status_code in (401, 403):
|
||||
if attempt < retries - 1:
|
||||
# Обновляем токен и пробуем снова
|
||||
self._authenticate()
|
||||
continue
|
||||
raise AvitoAuthError(f"Authentication failed after retries: {response.text}")
|
||||
|
||||
# Check rate limiting (429)
|
||||
if response.status_code == 429:
|
||||
if attempt < retries - 1:
|
||||
time.sleep(2 ** attempt) # Exponential backoff
|
||||
continue
|
||||
raise AvitoRateLimitError("Rate limit exceeded")
|
||||
|
||||
if response.status_code == 400:
|
||||
raise AvitoBadRequestError(f"Bad Request: {response.text}")
|
||||
|
||||
if response.status_code == 404:
|
||||
raise AvitoNotFoundError(f"Not Found: {response.text}")
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
if response.content:
|
||||
return response.json()
|
||||
return {}
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
if attempt < retries - 1:
|
||||
time.sleep(2 ** attempt)
|
||||
continue
|
||||
raise AvitoAPIError(f"Request failed: {str(e)}")
|
||||
|
||||
raise AvitoAPIError("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)
|
||||
19
backend/avito_api/exceptions.py
Normal file
19
backend/avito_api/exceptions.py
Normal file
@@ -0,0 +1,19 @@
|
||||
class AvitoAPIError(Exception):
|
||||
"""Base exception for all Avito API errors."""
|
||||
pass
|
||||
|
||||
class AvitoAuthError(AvitoAPIError):
|
||||
"""Raised when authentication fails (HTTP 401 or 403)."""
|
||||
pass
|
||||
|
||||
class AvitoRateLimitError(AvitoAPIError):
|
||||
"""Raised when API rate limits are exceeded (HTTP 429)."""
|
||||
pass
|
||||
|
||||
class AvitoBadRequestError(AvitoAPIError):
|
||||
"""Raised when API returns HTTP 400."""
|
||||
pass
|
||||
|
||||
class AvitoNotFoundError(AvitoAPIError):
|
||||
"""Raised when API returns HTTP 404."""
|
||||
pass
|
||||
15
backend/avito_api/services/items.py
Normal file
15
backend/avito_api/services/items.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from typing import Dict, Any, Optional
|
||||
from ..client import AvitoClient
|
||||
|
||||
class ItemsService:
|
||||
"""Service to handle Avito Items (Listings)."""
|
||||
|
||||
def __init__(self, client: AvitoClient):
|
||||
self.client = client
|
||||
|
||||
def get_info(self, item_id: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get info about a specific item.
|
||||
Endpoint: /core/v1/items/{item_id}
|
||||
"""
|
||||
return self.client.get(f"/core/v1/items/{item_id}")
|
||||
29
backend/avito_api/services/messenger.py
Normal file
29
backend/avito_api/services/messenger.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from typing import Dict, Any, Optional
|
||||
from ..client import AvitoClient
|
||||
|
||||
class MessengerService:
|
||||
"""Service to handle Avito Messenger (Chats)."""
|
||||
|
||||
def __init__(self, client: AvitoClient):
|
||||
self.client = client
|
||||
|
||||
def get_chats(self, user_id: str, limit: int = 100, offset: int = 0) -> Dict[str, Any]:
|
||||
"""
|
||||
Get list of active chats for a user.
|
||||
Endpoint: /messenger/v2/accounts/{user_id}/chats
|
||||
"""
|
||||
params = {"limit": limit, "offset": offset}
|
||||
return self.client.get(f"/messenger/v2/accounts/{user_id}/chats", params=params)
|
||||
|
||||
def send_message(self, user_id: str, chat_id: str, text: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Send a text message to a specific chat.
|
||||
Endpoint: /messenger/v1/accounts/{user_id}/chats/{chat_id}/messages
|
||||
"""
|
||||
payload = {
|
||||
"message": {
|
||||
"text": text
|
||||
},
|
||||
"type": "text"
|
||||
}
|
||||
return self.client.post(f"/messenger/v1/accounts/{user_id}/chats/{chat_id}/messages", data=payload)
|
||||
Reference in New Issue
Block a user