Spaces:
Running
Running
File size: 7,990 Bytes
403c184 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
#!/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() |