53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
# api_client.py
|
|
import requests
|
|
import logging
|
|
from rest_framework.response import Response
|
|
from .constants import API_URLS, CREDENTIALS
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class APIClient:
|
|
@staticmethod
|
|
def get_token(url):
|
|
"""Получение токена авторизации"""
|
|
payload = {
|
|
"UserName": CREDENTIALS["USERNAME"],
|
|
"Password": CREDENTIALS["PASSWORD"]
|
|
}
|
|
try:
|
|
response = requests.post(url, json=payload)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
return data["Value"]["Token"] if data.get("IsSuccess") else None
|
|
except Exception as e:
|
|
logger.error(f"Token request error: {str(e)}")
|
|
return None
|
|
|
|
@staticmethod
|
|
def make_request(url, token, payload=None, timeout=10):
|
|
"""Выполнение API-запроса"""
|
|
headers = {
|
|
"Authorization": f"Bearer {token}",
|
|
"Content-Type": "application/json"
|
|
}
|
|
try:
|
|
response = requests.post(
|
|
url,
|
|
json=payload or {},
|
|
headers=headers,
|
|
timeout=timeout
|
|
)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
except Exception as e:
|
|
logger.error(f"API request error: {str(e)}")
|
|
return None
|
|
|
|
@staticmethod
|
|
def create_response(status, message=None, data=None, status_code=200):
|
|
"""Формирование стандартного ответа API"""
|
|
return Response({
|
|
"status": status,
|
|
"message": message,
|
|
"data": data
|
|
}, status=status_code) |