Spaces:
Running
Running
| #!/usr/bin/env python3 | |
| """ | |
| Debug script to test Wildberries API integration | |
| This script will help identify why no data is being retrieved from the API | |
| """ | |
| import os | |
| import sys | |
| import logging | |
| from datetime import datetime, timedelta | |
| # Set up detailed logging | |
| logging.basicConfig( | |
| level=logging.DEBUG, | |
| format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # Import our modules | |
| try: | |
| from wildberries_client import WildberriesAPI, WildberriesAPIError | |
| from config import get_config | |
| import utils | |
| except ImportError as e: | |
| logger.error(f"Failed to import modules: {e}") | |
| sys.exit(1) | |
| def test_api_configuration(): | |
| """Test API configuration and token validation""" | |
| logger.info("=== Testing API Configuration ===") | |
| config = get_config() | |
| logger.info(f"Demo mode: {config.demo_mode}") | |
| logger.info(f"Debug mode: {config.debug_mode}") | |
| # Check if there's a token in environment (for testing only - app uses Gradio input) | |
| token_env = os.getenv("WILDBERRIES_API_TOKEN") | |
| logger.info(f"API configured: {config.is_configured(token_env)}") | |
| logger.info(f"Token from env (for testing): {'***set***' if token_env else 'NOT SET'}") | |
| logger.info("Note: Production app only accepts tokens via Gradio interface") | |
| if token_env: | |
| logger.info(f"Token length: {len(token_env)}") | |
| logger.info(f"Token valid format: {config.validate_token(token_env)}") | |
| logger.info(f"Token starts with: {token_env[:10]}...") | |
| # Check endpoints | |
| endpoints = config.get_endpoints() | |
| logger.info(f"Sales endpoint: {endpoints['sales']}") | |
| logger.info(f"Stocks endpoint: {endpoints['stocks']}") | |
| return config | |
| def test_client_initialization(token=None): | |
| """Test client initialization""" | |
| logger.info("=== Testing Client Initialization ===") | |
| try: | |
| if token: | |
| logger.info("Using provided token") | |
| else: | |
| token = os.getenv("WILDBERRIES_API_TOKEN") | |
| logger.info("Using token from environment") | |
| if not token: | |
| logger.warning("No token available - client will not be configured") | |
| return None | |
| client = WildberriesAPI(token) | |
| logger.info(f"Client created successfully") | |
| logger.info(f"Client is_configured: {client.is_configured}") | |
| return client | |
| except Exception as e: | |
| logger.error(f"Failed to create client: {e}") | |
| return None | |
| def test_api_request(client, endpoint_type="sales"): | |
| """Test specific API request""" | |
| logger.info(f"=== Testing {endpoint_type.upper()} API Request ===") | |
| if not client: | |
| logger.error("No client available") | |
| return None | |
| if not client.is_configured: | |
| logger.error("Client is not configured with valid token") | |
| return None | |
| try: | |
| # Test different date ranges | |
| date_from = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d") | |
| date_to = datetime.now().strftime("%Y-%m-%d") | |
| logger.info(f"Requesting {endpoint_type} data from {date_from} to {date_to}") | |
| if endpoint_type == "sales": | |
| data = client.get_sales(date_from, date_to) | |
| elif endpoint_type == "stocks": | |
| data = client.get_stocks(date_from, date_to) | |
| elif endpoint_type == "orders": | |
| data = client.get_orders(date_from, date_to) | |
| else: | |
| logger.error(f"Unknown endpoint type: {endpoint_type}") | |
| return None | |
| logger.info(f"Response received: {type(data)}") | |
| logger.info(f"Data shape: {data.shape if hasattr(data, 'shape') else 'No shape'}") | |
| logger.info(f"Data empty: {data.empty if hasattr(data, 'empty') else 'No empty attr'}") | |
| if hasattr(data, 'columns'): | |
| logger.info(f"Columns: {list(data.columns)}") | |
| if not data.empty: | |
| logger.info(f"First few rows:\n{data.head()}") | |
| else: | |
| logger.warning("Data is empty!") | |
| return data | |
| except WildberriesAPIError as e: | |
| logger.error(f"Wildberries API Error: {e}") | |
| return None | |
| except Exception as e: | |
| logger.error(f"Unexpected error: {e}") | |
| import traceback | |
| logger.error(traceback.format_exc()) | |
| return None | |
| def test_demo_data(): | |
| """Test demo data generation""" | |
| logger.info("=== Testing Demo Data Generation ===") | |
| try: | |
| # Test sales data | |
| sales_data = utils.load_demo_sales_data("week") | |
| logger.info(f"Demo sales data shape: {sales_data.shape}") | |
| logger.info(f"Demo sales columns: {list(sales_data.columns)}") | |
| # Test inventory data | |
| inventory_data = utils.load_demo_inventory_data() | |
| logger.info(f"Demo inventory data shape: {inventory_data.shape}") | |
| logger.info(f"Demo inventory columns: {list(inventory_data.columns)}") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Demo data generation failed: {e}") | |
| return False | |
| def test_api_endpoints_directly(client): | |
| """Test API endpoints directly with curl-like requests""" | |
| logger.info("=== Testing Direct API Endpoints ===") | |
| if not client or not client.is_configured: | |
| logger.error("No configured client available") | |
| return | |
| import requests | |
| # Test the exact endpoint from working curl | |
| url = "https://statistics-api.wildberries.ru/api/v5/supplier/reportDetailByPeriod" | |
| headers = client._get_headers() | |
| logger.info(f"Headers: {headers}") | |
| date_from = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d") | |
| date_to = datetime.now().strftime("%Y-%m-%d") | |
| params = { | |
| "dateFrom": date_from, | |
| "dateTo": date_to, | |
| "limit": 100 | |
| } | |
| logger.info(f"URL: {url}") | |
| logger.info(f"Params: {params}") | |
| try: | |
| response = requests.get(url, headers=headers, params=params, timeout=30) | |
| logger.info(f"Response status: {response.status_code}") | |
| logger.info(f"Response headers: {dict(response.headers)}") | |
| if response.status_code == 200: | |
| try: | |
| data = response.json() | |
| logger.info(f"Response type: {type(data)}") | |
| logger.info(f"Response length: {len(data) if isinstance(data, list) else 'Not a list'}") | |
| if isinstance(data, list) and len(data) > 0: | |
| logger.info(f"First item keys: {list(data[0].keys()) if isinstance(data[0], dict) else 'Not a dict'}") | |
| logger.info(f"First item: {data[0]}") | |
| elif isinstance(data, dict): | |
| logger.info(f"Response keys: {list(data.keys())}") | |
| except Exception as e: | |
| logger.error(f"Failed to parse JSON: {e}") | |
| logger.info(f"Raw response: {response.text[:500]}") | |
| else: | |
| logger.error(f"HTTP Error: {response.text}") | |
| except Exception as e: | |
| logger.error(f"Request failed: {e}") | |
| def main(): | |
| """Main debug function""" | |
| logger.info("Starting Wildberries API Debug Session") | |
| logger.info("=" * 50) | |
| # Test 1: Configuration | |
| config = test_api_configuration() | |
| # Test 2: Demo data (baseline) | |
| demo_works = test_demo_data() | |
| # Test 3: Client initialization | |
| client = test_client_initialization() | |
| if client: | |
| # Test 4: API requests | |
| sales_data = test_api_request(client, "sales") | |
| stocks_data = test_api_request(client, "stocks") | |
| # Test 5: Direct endpoint test | |
| test_api_endpoints_directly(client) | |
| else: | |
| logger.warning("Skipping API tests - no client available") | |
| logger.info("=" * 50) | |
| logger.info("Debug session completed") | |
| if __name__ == "__main__": | |
| main() |