import asyncio import json import logging from typing import Union import utils from database import Marketplace from limiter import BatchLimiter from marketplaces.base import BaseMarketplaceApi class OzonMarketplaceApi(BaseMarketplaceApi): def __init__(self, marketplace: Marketplace): self.marketplace = marketplace self.is_valid = True try: auth_data = json.loads(marketplace.auth_data) except Exception: logging.error(f"Couldn't load auth data for marketplace [{self.marketplace.id}]") self.is_valid = False return client_id = auth_data.get('clientId') self.limiter_key = str(marketplace.company_id) + str(client_id) self.headers = { 'Client-Id': client_id, 'Api-Key': auth_data.get('clientToken') } def get_headers(self): return self.headers @property def api_url(self): return 'https://api-seller.ozon.ru' async def update_stocks(self, data: Union[list, dict]): if type(data) is not list: return if not self.is_valid: return max_stocks = 100 chunks = utils.chunk_list(data, max_stocks) limiter = BatchLimiter() async def send_stock_chunk(chunk): if not self.is_valid: return try: await limiter.acquire_ozon(self.limiter_key) request_data = {'stocks': chunk} response = await self._method('POST', '/v2/products/stocks', data=request_data) response = await response.json() error_message = response.get('message') error_code = response.get('code') if error_message: logging.warning( f'Error occurred when sending stocks to [{self.marketplace.id}]: {error_message} ({error_code})') self.is_valid = False except Exception as e: logging.error( f'Exception occurred while sending stocks to marketplace ID [{self.marketplace.id}]: {str(e)}') self.is_valid = False tasks = [send_stock_chunk(chunk) for chunk in chunks] await asyncio.gather(*tasks)