### Get Product Descriptions using Producer-Consumer Pattern in Python Source: https://context7.com/a-ulianov/ozonapi/llms.txt Fetches detailed product descriptions asynchronously by implementing a producer-consumer pattern. The producer fetches product IDs and adds them to a queue, while consumers fetch descriptions from the queue. This approach is efficient for handling a large number of requests and managing rate limits. Dependencies include asyncio and specific modules from the ozonapi library. ```python import asyncio from ozonapi import SellerAPI, SellerAPIConfig from ozonapi.seller.schemas.products import ( ProductListRequest, ProductInfoDescriptionRequest ) # Configuration product_list_limit = 100 consumers_amount = 5 consumers_rps_max_limit = 6 queue_max_size = product_list_limit * consumers_amount product_descriptions = [] async def producer(queue): """Fetch product IDs and add to queue for description fetching.""" async with SellerAPI( config=SellerAPIConfig(log_level="INFO") ) as api: products_count = 0 last_id = "" while True: products_batch = await api.product_list( ProductListRequest(limit=product_list_limit, last_id=last_id) ) last_id = products_batch.result.last_id products_count += len(products_batch.result.items) for item in products_batch.result.items: await queue.put(item.product_id) api.logger.info( f"Added {products_count} of {products_batch.result.total} to queue" ) if products_count == products_batch.result.total: break async def consumer(queue): """Fetch product descriptions from queue.""" async with SellerAPI( config=SellerAPIConfig( log_level="INFO", max_requests_per_second=consumers_rps_max_limit ) ) as api: while True: product_id = await queue.get() product_description = await api.product_info_description( ProductInfoDescriptionRequest(product_id=product_id) ) product_descriptions.append(product_description.result) api.logger.info( f"Got description for product {product_description.result.id}" ) queue.task_done() async def main(): queue = asyncio.Queue(maxsize=queue_max_size) # Create consumer tasks [asyncio.create_task(consumer(queue)) for _ in range(consumers_amount)] # Run producer await producer(queue) # Wait for all tasks to complete await queue.join() if __name__ == "__main__": asyncio.run(main()) print(f"Fetched {len(product_descriptions)} descriptions") ``` -------------------------------- ### Get Product Price Information (Python) Source: https://context7.com/a-ulianov/ozonapi/llms.txt Retrieve detailed pricing information for products, including commissions, discounts, and marketing costs. This function uses the SellerAPI and supports fetching all product prices or specific products with filtering and pagination. It iterates through results to display prices, currencies, and commission percentages. ```python import asyncio from ozonapi import SellerAPI from ozonapi.seller.schemas.prices_and_stocks import ( ProductInfoPricesRequest, ProductInfoPricesFilter ) from ozonapi.seller.common.enumerations.products import Visibility async def main(): async with SellerAPI() as api: # Get all product prices result = await api.product_info_prices() for item in result.result.items: print(f"Product ID: {item.product_id}") print(f"Price: {item.price.price} {item.price.currency_code}") print(f"Old Price: {item.price.old_price}") print(f"Commission: {item.commissions.sales_percent}%") print("---") # Get prices for specific products with pagination result = await api.product_info_prices( ProductInfoPricesRequest( filter=ProductInfoPricesFilter( offer_id=["SKU-001", "SKU-002"], visibility=Visibility.VISIBLE ), limit=50, cursor="" # Use cursor from previous response for pagination ) ) # Next page if result.result.cursor: next_page = await api.product_info_prices( ProductInfoPricesRequest(cursor=result.result.cursor) ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Seller Account Information Source: https://context7.com/a-ulianov/ozonapi/llms.txt Shows how to retrieve detailed information about the seller's account, including company name, INN, and seller ID. It demonstrates accessing specific fields from the response object and printing the full response as a dictionary. ```python import asyncio from pprint import pprint from ozonapi import SellerAPI async def main(): # OZON_SELLER_CLIENT_ID and OZON_SELLER_API_KEY in .env async with SellerAPI() as api: result = await api.seller_info() # Access specific fields print(f"Company Name: {result.company.name}") print(f"INN: {result.company.inn}") print(f"Seller ID: {result.seller_id}") # Full response as dictionary pprint(result.model_dump()) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Product Assortment Limits with Python Source: https://context7.com/a-ulianov/ozonapi/llms.txt Retrieves and displays current limits for product assortment creation and updates using the Ozon Seller API. It shows daily creation limits, daily update limits, and total limits available for products. ```python import asyncio from pprint import pprint from ozonapi import SellerAPI, SellerAPIConfig async def main(): async with SellerAPI( config=SellerAPIConfig(log_level="DEBUG") ) as api: result = await api.product_info_limit() # Access limit information print(f"Daily Create Limit: {result.result.daily_create}") print(f"Daily Update Limit: {result.result.daily_update}") print(f"Total Limit: {result.result.total}") # Full response pprint(result.model_dump()) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Product Stock Information (Python) Source: https://context7.com/a-ulianov/ozonapi/llms.txt Retrieve current inventory levels and warehouse stock details for products. This function allows fetching stock information for all products or specific products filtered by offer ID, product ID, and visibility. It displays product ID, offer ID, present stock, and reserved stock quantities. ```python import asyncio from ozonapi import SellerAPI from ozonapi.seller.schemas.prices_and_stocks import ( ProductInfoStocksRequest, ProductInfoStocksFilter ) async def main(): async with SellerAPI() as api: # Get all stock information result = await api.product_info_stocks() for item in result.result.items: print(f"Product ID: {item.product_id}") print(f"Offer ID: {item.offer_id}") print(f"Present: {item.stocks.present}") print(f"Reserved: {item.stocks.reserved}") print("---") # Get stock for specific products result = await api.product_info_stocks( ProductInfoStocksRequest( filter=ProductInfoStocksFilter( offer_id=["SKU-001"], product_id=[12345], visibility="ALL" ), limit=100, last_id="" ) ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize SellerAPI Client with Authentication Options Source: https://context7.com/a-ulianov/ozonapi/llms.txt Demonstrates how to initialize the SellerAPI client using API keys loaded from environment variables, explicit credentials, or OAuth tokens. It shows basic usage by fetching seller information and product lists. ```python import asyncio from ozonapi import SellerAPI, SellerAPIConfig async def main(): # Using API key authentication (loads from .env automatically) async with SellerAPI() as api: result = await api.seller_info() print(f"Company: {result.company.name}") print(f"INN: {result.company.inn}") # Using explicit credentials async with SellerAPI( client_id="your_client_id", api_key="your_api_key" ) as api: seller_info = await api.seller_info() print(seller_info.model_dump()) # Using OAuth token async with SellerAPI(token="your_oauth_token") as api: products = await api.product_list() print(f"Total products: {products.result.total}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Authenticate and Fetch Seller Info using Environment Variables in Python Source: https://context7.com/a-ulianov/ozonapi/llms.txt Shows how to use the Ozon Seller API in Python, automatically loading configuration from a .env file. It authenticates the API client and fetches the authenticated seller's company name. ```python import asyncio from ozonapi import SellerAPI async def main(): # Configuration automatically loaded from .env async with SellerAPI() as api: result = await api.seller_info() print(f"Authenticated as: {result.company.name}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Configure Ozon API with .env File Source: https://context7.com/a-ulianov/ozonapi/llms.txt Illustrates how to configure the Ozon API client using environment variables defined in a .env file. This method simplifies credential management and allows for customization of rate limiting, timeouts, and logging. ```bash # .env file OZON_SELLER_CLIENT_ID=your_client_id OZON_SELLER_API_KEY=your_api_key # Or use OAuth OZON_SELLER_TOKEN=your_oauth_token # Rate limiting OZON_SELLER_MAX_REQUESTS_PER_SECOND=27 # Timeouts and retries OZON_SELLER_REQUEST_TIMEOUT=60.0 OZON_SELLER_MAX_RETRIES=5 OZON_SELLER_RETRY_MIN_WAIT=2.0 OZON_SELLER_RETRY_MAX_WAIT=10.0 # Logging OZON_SELLER_LOG_LEVEL=INFO OZON_SELLER_LOG_FILE=ozon_api.log OZON_SELLER_LOG_MAX_BYTES=10485760 OZON_SELLER_LOG_BACKUP_FILES_COUNT=5 ``` -------------------------------- ### Configure SellerAPI Client with Custom Settings Source: https://context7.com/a-ulianov/ozonapi/llms.txt Illustrates advanced configuration of the SellerAPI client, including custom rate limiting, retry logic, request timeouts, and detailed logging options. It shows how to apply these settings and use the client's logger. ```python import asyncio from ozonapi import SellerAPI, SellerAPIConfig async def main(): # Create custom configuration config = SellerAPIConfig( client_id="your_client_id", api_key="your_api_key", max_requests_per_second=25, # Conservative rate limit request_timeout=60.0, # 60 second timeout max_retries=3, # Max 3 retry attempts retry_min_wait=2.0, # Min 2 seconds between retries retry_max_wait=10.0, # Max 10 seconds between retries log_level="DEBUG", # Enable debug logging log_file="ozon_api.log", # Log to file log_max_bytes=10485760, # 10MB log file size log_backup_files_count=5 # Keep 5 backup log files ) async with SellerAPI(config=config) as api: # Configuration is applied to all API calls warehouses = await api.warehouse_list() print(f"Available warehouses: {len(warehouses.result)}") # Access logger for custom logging api.logger.info("Custom log message") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### List Products with Pagination and Filtering (Python) Source: https://context7.com/a-ulianov/ozonapi/llms.txt Retrieve product listings with support for filtering by offer ID, visibility, and pagination. This function utilizes the SellerAPI to fetch product data, allowing for efficient management of large inventories. It demonstrates basic retrieval, filtered retrieval, and a loop for paginating through all available products. ```python import asyncio from ozonapi import SellerAPI from ozonapi.seller.schemas.products import ProductListRequest, ProductListFilter from ozonapi.seller.common.enumerations.products import Visibility async def main(): async with SellerAPI() as api: # Basic product list (uses default pagination) result = await api.product_list() print(f"Total products: {result.result.total}") # Filtered product list with specific offer IDs result = await api.product_list( ProductListRequest( filter=ProductListFilter( offer_id=["SKU-001", "SKU-002"], visibility=Visibility.ALL ), limit=100 ) ) # Pagination through all products last_id = "" all_products = [] while True: response = await api.product_list( ProductListRequest(limit=100, last_id=last_id) ) all_products.extend(response.result.items) if len(response.result.items) == 0: break last_id = response.result.last_id print(f"Fetched {len(all_products)} of {response.result.total}") print(f"Total fetched: {len(all_products)}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### List Warehouses with Delivery Methods and Status using Python Source: https://context7.com/a-ulianov/ozonapi/llms.txt Fetches and iterates through all warehouses associated with the seller account, displaying key information such as warehouse ID, name, status, type, and whether acts can be printed in advance. ```python import asyncio from ozonapi import SellerAPI async def main(): async with SellerAPI() as api: result = await api.warehouse_list() for warehouse in result.result: print(f"Warehouse ID: {warehouse.warehouse_id}") print(f"Name: {warehouse.name}") print(f"Status: {warehouse.status}") print(f"Type: {warehouse.warehouse_type}") print(f"Can Print Acts: {warehouse.can_print_act_in_advance}") print("---") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Manage Multiple Seller Accounts Concurrently with Python Source: https://context7.com/a-ulianov/ozonapi/llms.txt Demonstrates how to manage multiple seller accounts simultaneously using asynchronous programming in Python. It fetches seller information, product counts, and warehouse counts for each account, handling potential errors and rate limit isolation. ```python import asyncio from ozonapi import SellerAPI async def fetch_account_data(config): """Fetch data for a single account.""" async with SellerAPI(**config) as api: try: seller_info = await api.seller_info() products = await api.product_list() warehouses = await api.warehouse_list() return { "client_id": config["client_id"], "company": seller_info.company.name, "product_count": products.result.total, "warehouse_count": len(warehouses.result), "status": "success" } except Exception as e: return { "client_id": config["client_id"], "status": "error", "error": str(e) } async def main(): # Multiple account configurations accounts = [ {"client_id": "client_1", "api_key": "key_1"}, {"client_id": "client_2", "api_key": "key_2"}, {"token": "oauth_token_3"} # OAuth account ] # Fetch data concurrently tasks = [fetch_account_data(config) for config in accounts] results = await asyncio.gather(*tasks, return_exceptions=True) # Process results for result in results: if isinstance(result, Exception): print(f"Error: {result}") elif result["status"] == "success": print(f"Account {result['client_id']}: {result['product_count']} products") else: print(f"Account {result['client_id']}: {result['error']}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### List FBO Orders with Python Source: https://context7.com/a-ulianov/ozonapi/llms.txt Retrieves FBO (Fulfilled by Ozon) orders, allowing filtering by date range and status. It utilizes the SellerAPI to make the request and processes the results to print order details. Dependencies include asyncio, datetime, and specific modules from the ozonapi library. ```python import asyncio import datetime from ozonapi import SellerAPI from ozonapi.seller.schemas.fbo import PostingFBOListRequest from ozonapi.seller.schemas.entities.postings import PostingFilter, PostingFilterWith from ozonapi.seller.common.enumerations.postings import PostingStatus from ozonapi.seller.common.enumerations.requests import SortingDirection async def main(): async with SellerAPI() as api: result = await api.posting_fbo_list( PostingFBOListRequest( dir=SortingDirection.ASC, filter=PostingFilter( since=datetime.datetime.now() - datetime.timedelta(days=30), to=datetime.datetime.now(), status=PostingStatus.DELIVERED ), limit=100, offset=0, translit=False, with_=PostingFilterWith( analytics_data=True, financial_data=True, legal_info=True ) ) ) print(f"Found {len(result.result.postings)} postings") for posting in result.result.postings: print(f"Order: {posting.order_number}") print(f"Status: {posting.status}") print(f"Delivery: {posting.delivery_method.name}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Update Product Stocks using Ozon Seller API (Python) Source: https://context7.com/a-ulianov/ozonapi/llms.txt Updates the inventory quantities for multiple products across specified warehouses. It utilizes the SellerAPI and ProductStock schema for structured requests and provides error checking for failed updates. ```Python import asyncio from ozonapi import SellerAPI from ozonapi.seller.schemas.prices_and_stocks import ( ProductsStocksRequest, ProductStock ) async def main(): async with SellerAPI() as api: # Update stock for multiple products result = await api.products_stocks( ProductsStocksRequest( stocks=[ ProductStock( offer_id="SKU-001", product_id=12345, stock=100, warehouse_id=12345678 ), ProductStock( offer_id="SKU-002", stock=50, warehouse_id=12345678 ) ] ) ) # Check for errors for error in result.result.errors: print(f"Error updating {error.offer_id}: {error.message}") # Check successful updates print(f"Successfully updated {len(result.result.updated)} products") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Update Product Prices using Ozon Seller API (Python) Source: https://context7.com/a-ulianov/ozonapi/llms.txt Updates product pricing information, including old prices, premium prices, and currency codes. It uses the SellerAPI and ProductImportPricesRequest schema for managing price updates and reports on errors and successful updates. ```Python import asyncio from ozonapi import SellerAPI from ozonapi.seller.schemas.prices_and_stocks import ( ProductImportPricesRequest, ProductPrice ) async def main(): async with SellerAPI() as api: # Update prices for multiple products result = await api.product_import_prices( ProductImportPricesRequest( prices=[ ProductPrice( offer_id="SKU-001", price="1299.99", old_price="1499.99", # Crossed-out price premium_price="1199.99", # Premium subscription price currency_code="RUB", auto_action_enabled="ENABLED" ), ProductPrice( product_id=12345, price="599.00", currency_code="RUB" ) ] ) ) # Check for errors for error in result.result.errors: print(f"Error: {error.offer_id} - {error.message}") print(f"Updated: {len(result.result.updated)}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### List Unfulfilled FBS Orders using Ozon Seller API (Python) Source: https://context7.com/a-ulianov/ozonapi/llms.txt Retrieves a list of unfulfilled FBS (Fulfilment by Seller) orders that require processing. It includes detailed shipment and product information, allowing for efficient order management. ```Python import asyncio from ozonapi import SellerAPI from ozonapi.seller.schemas.fbs import PostingFBSUnfulfilledListRequest from ozonapi.seller.common.enumerations.requests import SortingDirection from ozonapi.seller.common.enumerations.delivery import CutoffDeliveryGroup async def main(): async with SellerAPI() as api: # Get unfulfilled orders result = await api.posting_fbs_unfulfilled_list( PostingFBSUnfulfilledListRequest( dir=SortingDirection.ASC, filter={"status": "awaiting_packaging"}, limit=50, offset=0, with_={"analytics_data": True, "financial_data": True} ) ) print(f"Total unfulfilled: {result.result.count}") for posting in result.result.postings: print(f"\nPosting Number: {posting.posting_number}") print(f"Order Number: {posting.order_number}") print(f"Status: {posting.status}") print(f"Shipment Date: {posting.shipment_date}") print(f"In Process At: {posting.in_process_at}") # Product details for product in posting.products: print(f" - {product.name}: {product.quantity} pcs") print(f" SKU: {product.sku}, Price: {product.price}") if __name__ == "__main__": asyncio.run(main()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.