Troubleshooting Guide¶
This guide helps you diagnose and resolve common issues with the pCloud SDK Python v2.0.
Table of Contents¶
- Quick Diagnostics
- Authentication Issues
- Network Problems
- Upload/Download Issues
- Performance Issues
- Token Management Issues
- Error Codes Reference
- Debug Mode
- Getting Help
Quick Diagnostics¶
Health Check Script¶
Run this script to quickly diagnose common issues:
#!/usr/bin/env python3
"""
pCloud SDK Health Check
Quick diagnostic tool for common issues
"""
import os
import sys
import time
import tempfile
from pcloud_sdk import PCloudSDK, PCloudException
def health_check():
"""Comprehensive health check for pCloud SDK"""
print("<รฅ pCloud SDK Health Check")
print("=" * 40)
issues_found ๐พ0
# Test 1: Import and version check
print("\n1รฃ Testing SDK Import...")
try:
import pcloud_sdk
print(f" SDK version: {pcloud_sdk.__version__}")
except ImportError as e:
print(f" L Import failed: {e}")
print(" =ยก Solution: pip install pcloud-sdk-python")
issues_found +๐พ1
# Test 2: Network connectivity
print("\n2รฃ Testing Network Connectivity...")
try:
import requests
response ๐พrequests.get("https://api.pcloud.com", timeout=10)
if response.status_code =๐พ200:
print(" pCloud API is reachable")
else:
print(f" ย pCloud API returned status: {response.status_code}")
except Exception as e:
print(f" L Network connectivity issue: {e}")
print(" =ยก Check your internet connection")
issues_found +๐พ1
# Test 3: Authentication
print("\n3รฃ Testing Authentication...")
try:
sdk ๐พPCloudSDK()
# Check for saved credentials
cred_info ๐พsdk.get_credentials_info()
if cred_info.get('email'):
print(f" =ร Found saved credentials for: {cred_info['email']}")
print(f" =ร
Credentials age: {cred_info.get('age_days', 0):.1f} days")
# Test if credentials work
try:
sdk.login()
email ๐พsdk.user.get_user_email()
print(f" Authentication successful: {email}")
except Exception as e:
print(f" L Saved credentials invalid: {e}")
print(" =ยก Try logging in with fresh credentials")
issues_found +๐พ1
else:
print(" 9 No saved credentials found")
print(" =ยก Run: sdk.login('email', 'password') to authenticate")
except Exception as e:
print(f" L Authentication test failed: {e}")
issues_found +๐พ1
# Test 4: Basic operations (if authenticated)
if 'sdk' in locals() and sdk.is_authenticated():
print("\n4รฃ Testing Basic Operations...")
try:
# Test folder listing
root_contents ๐พsdk.folder.list_root()
print(f" Folder listing works ({len(root_contents['contents'])} items)")
# Test file upload/download
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tmp:
tmp.write("Health check test file")
test_file ๐พtmp.name
try:
result ๐พsdk.file.upload(test_file, filename="health_check.txt")
file_id ๐พresult['metadata'][0]['fileid']
print(" File upload works")
# Test download
download_dir ๐พtempfile.mkdtemp()
success ๐พsdk.file.download(file_id, download_dir)
if success:
print(" File download works")
else:
print(" L File download failed")
issues_found +๐พ1
# Cleanup
sdk.file.delete(file_id)
os.unlink(test_file)
import shutil
shutil.rmtree(download_dir)
except Exception as e:
print(f" L File operations failed: {e}")
issues_found +๐พ1
except Exception as e:
print(f" L Basic operations test failed: {e}")
issues_found +๐พ1
# Summary
print(f"\n=ร Health Check Summary:")
if issues_found =๐พ0:
print(" <ย All tests passed! SDK is working correctly.")
else:
print(f" ย Found {issues_found} issue(s). See solutions above.")
return issues_found =๐พ0
if __name__ =๐พ"__main__":
success ๐พhealth_check()
sys.exit(0 if success else 1)
Quick Environment Check¶
def check_environment():
"""Quick environment diagnostic"""
print("=
Environment Check:")
# Python version
import sys
print(f" Python: {sys.version}")
# Operating system
import platform
print(f" OS: {platform.system()} {platform.release()}")
# Required packages
try:
import requests
print(f" requests: {requests.__version__}")
except ImportError:
print(" L requests not installed")
try:
import pcloud_sdk
print(f" pcloud-sdk-python: {pcloud_sdk.__version__}")
except ImportError:
print(" L pcloud-sdk-python not installed")
# Network configuration
try:
import socket
hostname ๐พsocket.gethostname()
local_ip ๐พsocket.gethostbyname(hostname)
print(f" Network: {hostname} ({local_ip})")
except:
print(" ย Network info unavailable")
check_environment()
Authentication Issues¶
Issue: "Invalid credentials" or "Login failed"¶
Symptoms: - Login fails with email/password - Error messages about invalid credentials
Solutions:
-
Verify credentials:
-
Try different server locations:
-
Check for special characters:
Issue: "Token expired" or "Authentication required"¶
Symptoms: - Operations fail with authentication errors - Previously working credentials stop working
Solutions:
-
Force re-authentication:
-
Check token age:
Issue: OAuth2 authentication problems¶
Symptoms: - OAuth2 flow fails - Invalid authorization code errors
Solutions:
-
Verify OAuth2 setup:
# Check your app configuration sdk ๐พPCloudSDK( app_key="your_client_id", # From pCloud developer console app_secret="your_client_secret", auth_type="oauth2" ) # Ensure redirect URI matches exactly redirect_uri ๐พ"http://localhost:8000/callback" # Must match app config auth_url ๐พsdk.get_auth_url(redirect_uri) print(f"Authorization URL: {auth_url}") -
Debug OAuth2 callback:
def debug_oauth_callback(callback_url): """Extract and validate OAuth2 code from callback URL""" from urllib.parse import urlparse, parse_qs parsed ๐พurlparse(callback_url) params ๐พparse_qs(parsed.query) if 'code' in params: code ๐พparams['code'][0] print(f" Authorization code: {code}") return code elif 'error' in params: error ๐พparams['error'][0] print(f"L OAuth2 error: {error}") return None else: print("L No code or error in callback URL") return None # Usage callback_url ๐พinput("Paste the full callback URL: ") code ๐พdebug_oauth_callback(callback_url) if code: token_info ๐พsdk.authenticate(code)
Network Problems¶
Issue: Connection timeouts or network errors¶
Symptoms: - Operations fail with timeout errors - "Cannot connect to pCloud servers" messages
Solutions:
-
Test network connectivity:
import requests import time def test_network_connectivity(): """Test connection to pCloud servers""" servers ๐พ{ "EU": "https://eapi.pcloud.com", "US": "https://api.pcloud.com" } for region, url in servers.items(): try: start_time ๐พtime.time() response ๐พrequests.get(url, timeout=10) elapsed ๐พtime.time() - start_time print(f" {region} server: {response.status_code} ({elapsed:.2f}s)") except requests.exceptions.Timeout: print(f"รฐ {region} server: Timeout") except requests.exceptions.ConnectionError: print(f"L {region} server: Connection failed") except Exception as e: print(f"L {region} server: {e}") test_network_connectivity() -
Adjust timeout settings:
-
Implement retry logic:
import time import random def retry_with_backoff(func, max_retries=3, base_delay=1): """Retry function with exponential backoff""" for attempt in range(max_retries): try: return func() except Exception as e: if attempt =๐พmax_retries - 1: raise e delay ๐พbase_delay * (2 ** attempt) + random.uniform(0, 1) print(f"= Retry {attempt + 1}/{max_retries} in {delay:.1f}s: {e}") time.sleep(delay) # Usage def upload_operation(): return sdk.file.upload("file.txt") result ๐พretry_with_backoff(upload_operation)
Issue: Proxy or firewall blocking connections¶
Symptoms: - SSL certificate errors - Connection refused errors - Proxy authentication required
Solutions:
-
Configure proxy settings:
-
Test with different network:
Upload/Download Issues¶
Issue: Large file uploads failing¶
Symptoms: - Uploads stop partway through - Memory errors with large files - Timeout errors on large uploads
Solutions:
-
Monitor upload progress:
from pcloud_sdk.progress_utils import create_detailed_progress def robust_large_upload(file_path): """Upload large files with detailed monitoring""" file_size ๐พos.path.getsize(file_path) print(f"=ร File size: {file_size / (1024**3):.2f} GB") # Use detailed progress for monitoring progress ๐พcreate_detailed_progress("upload.log") try: result ๐พsdk.file.upload(file_path, progress_callback=progress) return result except Exception as e: print(f"L Upload failed: {e}") print("=ร Check upload.log for details") raise # Usage result ๐พrobust_large_upload("large_file.zip") -
Optimize chunk size:
from pcloud_sdk.config import Config # Adjust chunk size based on file size and network speed file_size ๐พos.path.getsize("large_file.zip") if file_size ๐ 1024**3: # ๐ 1GB Config.FILE_PART_SIZE ๐พ50 * 1024 * 1024 # 50MB chunks elif file_size ๐ 100 * 1024**2: # ๐ 100MB Config.FILE_PART_SIZE ๐พ20 * 1024 * 1024 # 20MB chunks else: Config.FILE_PART_SIZE ๐พ10 * 1024 * 1024 # 10MB chunks (default) print(f"=' Chunk size: {Config.FILE_PART_SIZE / (1024**2):.0f}MB") -
Implement upload resume:
def upload_with_resume(file_path, max_attempts=3): """Upload with resume capability""" for attempt in range(max_attempts): try: print(f"=รค Upload attempt {attempt + 1}/{max_attempts}") def progress_callback(bytes_transferred, total_bytes, percentage, speed, **kwargs): # Save progress for potential resume status ๐พkwargs.get('status', 'progress') if status =๐พ'error': print(f"=ยพ Progress saved: {percentage:.1f}%") result ๐พsdk.file.upload(file_path, progress_callback=progress_callback) print(" Upload completed successfully") return result except Exception as e: print(f"L Attempt {attempt + 1} failed: {e}") if attempt โฑmax_attempts - 1: print("= Retrying...") time.sleep(5) else: print("L All attempts failed") raise # Usage result ๐พupload_with_resume("large_file.zip")
Issue: Download corruption or incomplete downloads¶
Symptoms: - Downloaded files are corrupted - Downloads stop before completion - File size mismatches
Solutions:
-
Verify download integrity:
import hashlib def verify_download(file_id, local_path): """Verify downloaded file integrity""" # Get file info from pCloud try: file_info ๐พsdk.file.get_info(file_id) expected_size ๐พfile_info.get('size', 0) # Check local file if os.path.exists(local_path): actual_size ๐พos.path.getsize(local_path) if actual_size =๐พexpected_size: print(f" File size matches: {actual_size:,} bytes") return True else: print(f"L Size mismatch: expected {expected_size:,}, got {actual_size:,}") return False else: print(f"L Downloaded file not found: {local_path}") return False except Exception as e: print(f"L Verification failed: {e}") return False # Usage success ๐พsdk.file.download(file_id, "./downloads/") if success: downloaded_file ๐พ"./downloads/filename.ext" # Adjust path verify_download(file_id, downloaded_file) -
Download with retry:
def download_with_retry(file_id, destination, max_retries=3): """Download with automatic retry on failure""" for attempt in range(max_retries): try: print(f"=รฅ Download attempt {attempt + 1}/{max_retries}") success ๐พsdk.file.download(file_id, destination) if success: print(" Download completed") return True else: print("L Download returned False") except Exception as e: print(f"L Download failed: {e}") if attempt โฑmax_retries - 1: print("= Retrying in 5 seconds...") time.sleep(5) print("L All download attempts failed") return False # Usage success ๐พdownload_with_retry(file_id, "./downloads/")
Performance Issues¶
Issue: Slow upload/download speeds¶
Symptoms: - Transfer speeds much slower than expected - Operations taking excessively long
Solutions:
-
Benchmark network speed:
import time import tempfile def benchmark_upload_speed(): """Benchmark upload speed with test file""" # Create test file (1MB) test_size ๐พ1024 * 1024 with tempfile.NamedTemporaryFile(mode='wb', suffix='.dat', delete=False) as tmp: tmp.write(b'0' * test_size) test_file ๐พtmp.name try: start_time ๐พtime.time() result ๐พsdk.file.upload(test_file, filename="speed_test.dat") elapsed ๐พtime.time() - start_time speed_mbps ๐พ(test_size / elapsed) / (1024 * 1024) print(f"=ร Upload speed: {speed_mbps:.2f} MB/s") # Cleanup file_id ๐พresult['metadata'][0]['fileid'] sdk.file.delete(file_id) finally: os.unlink(test_file) benchmark_upload_speed() -
Optimize settings for performance:
def optimize_for_performance(): """Configure SDK for maximum performance""" from pcloud_sdk.config import Config # Increase chunk size for faster networks Config.FILE_PART_SIZE ๐พ20 * 1024 * 1024 # 20MB chunks # Increase timeout for large files sdk.app.set_curl_execution_timeout(3600) # 1 hour # Use minimal progress tracking from pcloud_sdk.progress_utils import create_minimal_progress return create_minimal_progress() progress ๐พoptimize_for_performance()
Issue: High memory usage¶
Symptoms: - Memory consumption increases during uploads - Out of memory errors - System becomes slow during transfers
Solutions:
-
Monitor memory usage:
import psutil import os def monitor_memory_usage(): """Monitor memory usage during operations""" process ๐พpsutil.Process(os.getpid()) def memory_callback(bytes_transferred, total_bytes, percentage, speed, **kwargs): memory_mb ๐พprocess.memory_info().rss / (1024 * 1024) print(f"=ร {percentage:.1f}% - Memory: {memory_mb:.1f}MB") return memory_callback # Usage memory_progress ๐พmonitor_memory_usage() result ๐พsdk.file.upload("large_file.zip", progress_callback=memory_progress) -
Reduce chunk size for large files:
Token Management Issues¶
Issue: Credentials not saving or loading¶
Symptoms: - SDK asks for login every time - Saved credentials not found - Permission errors with credential files
Solutions:
-
Check file permissions:
import os import stat def check_credentials_file(): """Check credentials file status""" token_file ๐พ".pcloud_credentials" if os.path.exists(token_file): # Check permissions file_stat ๐พos.stat(token_file) permissions ๐พstat.filemode(file_stat.st_mode) size ๐พfile_stat.st_size print(f"=ร Credentials file: {token_file}") print(f" Size: {size} bytes") print(f" Permissions: {permissions}") # Check if readable if os.access(token_file, os.R_OK): print(" File is readable") else: print(" L File is not readable") # Check if writable if os.access(token_file, os.W_OK): print(" File is writable") else: print(" L File is not writable") # Try to read content try: with open(token_file, 'r') as f: import json data ๐พjson.load(f) print(f" =รง Email: {data.get('email', 'Unknown')}") print(f" =ร Saved: {data.get('saved_at', 'Unknown')}") except Exception as e: print(f" L Cannot read file: {e}") else: print(f"L Credentials file not found: {token_file}") check_credentials_file() -
Fix file permissions:
def fix_credentials_permissions(): """Fix credentials file permissions""" token_file ๐พ".pcloud_credentials" if os.path.exists(token_file): try: # Set read/write for owner only os.chmod(token_file, 0o600) print(f" Fixed permissions for {token_file}") except Exception as e: print(f"L Cannot fix permissions: {e}") fix_credentials_permissions() -
Use custom credentials file:
Error Codes Reference¶
Common pCloud API Error Codes¶
| Code | Description | Solution |
|---|---|---|
| 1000 | Login failed | Check email/password, try different server |
| 2000 | File not found | Verify file ID exists |
| 2001 | Folder not found | Verify folder ID exists |
| 2003 | Access denied | Check permissions, re-authenticate |
| 2005 | File/folder already exists | Use different name or delete existing |
| 2008 | Name too long | Use shorter filename |
| 2009 | Invalid name | Use valid characters only |
| 4000 | Too many login attempts | Wait before retrying |
| 5000 | Internal error | Retry operation, contact support if persistent |
SDK-Specific Error Handling¶
from pcloud_sdk import PCloudException
def handle_pcloud_errors(func):
"""Decorator for comprehensive error handling"""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except PCloudException as e:
error_code ๐พgetattr(e, 'code', 5000)
error_msg ๐พstr(e).lower()
if error_code =๐พ1000:
print("= Authentication failed - check credentials")
elif error_code =๐พ2000:
print("=ร File not found - check file ID")
elif error_code =๐พ2001:
print("=ร Folder not found - check folder ID")
elif error_code =๐พ2003:
print("=ยซ Access denied - check permissions")
elif error_code =๐พ4000:
print("รฐ Rate limited - wait before retrying")
elif "quota" in error_msg:
print("=ยพ Storage quota exceeded")
elif "network" in error_msg:
print("< Network error - check connection")
else:
print(f"L pCloud error {error_code}: {e}")
return None
except Exception as e:
print(f"L Unexpected error: {e}")
return None
return wrapper
# Usage
@handle_pcloud_errors
def safe_upload(file_path):
return sdk.file.upload(file_path)
result ๐พsafe_upload("file.txt")
Debug Mode¶
Enable Detailed Logging¶
import logging
# Configure detailed logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('pcloud_debug.log'),
logging.StreamHandler()
]
)
# Enable debug for specific modules
logger ๐พlogging.getLogger('pcloud_sdk')
logger.setLevel(logging.DEBUG)
# Enable debug for requests library
logging.getLogger('urllib3').setLevel(logging.DEBUG)
Debug Helper Functions¶
def debug_request_response():
"""Debug HTTP requests and responses"""
import requests
import logging
# Enable HTTP debug logging
import http.client as http_client
http_client.HTTPConnection.debuglevel ๐พ1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log ๐พlogging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate ๐พTrue
def debug_sdk_state(sdk):
"""Print SDK state information"""
print("=
SDK Debug Information:")
print(f" Authenticated: {sdk.is_authenticated()}")
print(f" Token Manager: {sdk.token_manager_enabled}")
print(f" Token File: {sdk.token_file}")
print(f" Location ID: {sdk.app.get_location_id()}")
print(f" Auth Type: {sdk.app.get_auth_type()}")
cred_info ๐พsdk.get_credentials_info()
if cred_info.get('email'):
print(f" Saved Email: {cred_info['email']}")
print(f" Credentials Age: {cred_info.get('age_days', 0):.1f} days")
# Usage
debug_request_response() # Enable HTTP debugging
debug_sdk_state(sdk) # Print SDK state
Getting Help¶
Collecting Debug Information¶
When reporting issues, include this debug information:
def collect_debug_info():
"""Collect comprehensive debug information"""
import sys
import platform
import os
debug_info ๐พ{
'python_version': sys.version,
'platform': platform.platform(),
'pcloud_sdk_version': None,
'requests_version': None,
'environment': {},
'sdk_state': {},
'network_test': {}
}
# Package versions
try:
import pcloud_sdk
debug_info['pcloud_sdk_version'] ๐พpcloud_sdk.__version__
except:
debug_info['pcloud_sdk_version'] ๐พ'Not installed'
try:
import requests
debug_info['requests_version'] ๐พrequests.__version__
except:
debug_info['requests_version'] ๐พ'Not installed'
# Environment variables
for key in ['HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY']:
debug_info['environment'][key] ๐พos.environ.get(key, 'Not set')
# SDK state (if available)
try:
sdk ๐พPCloudSDK()
debug_info['sdk_state'] ๐พ{
'authenticated': sdk.is_authenticated(),
'token_manager': sdk.token_manager_enabled,
'credentials_exist': bool(sdk.get_credentials_info().get('email')),
'location_id': sdk.app.get_location_id()
}
except:
debug_info['sdk_state'] ๐พ'SDK not available'
# Network test
try:
import requests
response ๐พrequests.get('https://api.pcloud.com', timeout=10)
debug_info['network_test'] ๐พ{
'status': 'OK',
'status_code': response.status_code,
'response_time': 'Available'
}
except Exception as e:
debug_info['network_test'] ๐พ{
'status': 'ERROR',
'error': str(e)
}
return debug_info
# Usage
debug_data ๐พcollect_debug_info()
print("=ร Debug Information:")
for key, value in debug_data.items():
print(f" {key}: {value}")
Support Channels¶
- GitHub Issues: Report bugs and feature requests
- Documentation: Check other documentation files in the
docs/folder - Community Forums: Search for similar issues in pCloud community
- Stack Overflow: Tag questions with
pcloudandpython
Creating a Minimal Reproduction Case¶
When reporting issues, create a minimal example:
#!/usr/bin/env python3
"""
Minimal reproduction case for issue reporting
"""
from pcloud_sdk import PCloudSDK, PCloudException
def minimal_reproduction():
"""Minimal example that reproduces the issue"""
# Initialize SDK
sdk ๐พPCloudSDK()
# Attempt to reproduce the issue
try:
# Replace with your specific issue
sdk.login("test@example.com", "password")
result ๐พsdk.file.upload("test.txt")
print(f"Success: {result}")
except Exception as e:
print(f"Error: {e}")
# Include debug information
import traceback
traceback.print_exc()
if __name__ =๐พ"__main__":
minimal_reproduction()
This troubleshooting guide should help you resolve most common issues with the pCloud SDK. If you encounter persistent problems, don't hesitate to seek help through the support channels mentioned above.