A Python SDK for Switcher API
- π Quick Start
- π¦ Installation
- π§ Configuration
- π Usage Examples
- ποΈ Advanced Features
- π Snapshot Management
- π§ͺ Testing & Development
- π€ Contributing
The Switcher Client SDK for Python provides seamless integration with Switcher-API, enabling powerful feature flag management in your Python applications.
- π― Clean & Maintainable: Flexible and robust functions that keep your code organized
- π Local Mode: Work offline using snapshot files from your Switcher-API Domain
- π Silent Mode: Hybrid configuration with automatic fallback for connectivity issues
- π§ͺ Built-in Mocking: Easy implementation of automated testing with mock support
- β‘ Zero Latency: Local snapshot execution for high-performance scenarios
- π‘οΈ Secure: Built-in protection against ReDoS attacks with regex safety features
- π Monitoring: Comprehensive logging and error handling capabilities
Get up and running in just a few lines of code:
from switcher_client import Client
# Initialize the client
Client.build_context(
domain='My Domain',
url='https://api.switcherapi.com',
api_key='[YOUR_API_KEY]',
component='MyApp',
environment='default'
)
# Use feature flags
switcher = Client.get_switcher()
if switcher.is_on('FEATURE_TOGGLE'):
print("Feature is enabled!")Install the Switcher Client SDK using pip:
pip install switcher-client- Python: 3.9+ (supports 3.9, 3.10, 3.11, 3.12, 3.13)
- Operating System: Cross-platform (Windows, macOS, Linux)
Initialize the Switcher Client with your domain configuration:
from switcher_client import Client
Client.build_context(
domain='My Domain', # Your Switcher domain name
url='https://api.switcherapi.com', # Switcher-API endpoint (optional)
api_key='[YOUR_API_KEY]', # Your component's API key (optional)
component='MyApp', # Your application name (optional)
environment='default' # Environment ('default' for production)
)
switcher = Client.get_switcher()| Parameter | Required | Description | Default |
|---|---|---|---|
domain |
β | Your Switcher domain name | - |
url |
Switcher-API endpoint | https://api.switcherapi.com |
|
api_key |
API key for your component | - | |
component |
Your application identifier | - | |
environment |
Target environment | default |
Enable additional features like local mode, silent mode, and security options:
from switcher_client import Client, ContextOptions
Client.build_context(
domain='My Domain',
url='https://api.switcherapi.com',
api_key='[YOUR_API_KEY]',
component='MyApp',
environment='default',
options=ContextOptions(
local=True, # Enable local mode
logger=True, # π§ TODO: Enable logging
snapshot_location='./snapshot/', # Snapshot files location
snapshot_auto_update_interval=3, # Auto-update interval (seconds)
silent_mode='5m', # π§ TODO: Silent mode retry time
cert_path='./certs/ca.pem' # π§ TODO: Certificate path
)
)
switcher = Client.get_switcher()| Option | Type | Description | Default |
|---|---|---|---|
local |
bool |
Use local snapshot files only (zero latency) | False |
snapshot_location |
str |
Directory for snapshot files | './snapshot/' |
snapshot_auto_update_interval |
int |
Auto-update interval in seconds (0 = disabled) | 0 |
regex_safe |
bool |
Enable ReDoS attack protection | True |
regex_max_black_list |
int |
Max cached entries for failed regex | 50 |
regex_max_time_limit |
int |
Regex execution time limit (ms) | 3000 |
- ReDoS Protection: The
regex_safefeature prevents Regular Expression Denial of Service attacks - Certificate Support: Use custom certificates for secure API connections
- Time Limits: Configurable timeouts prevent long-running regex operations
β οΈ Security Note: Keepregex_safeenabled to protect against ReDoS attacks
The simplest way to check if a feature is enabled:
switcher = Client.get_switcher()
# Simple boolean check
if switcher.is_on('FEATURE_LOGIN_V2'):
# Use new login system
new_login()
else:
# Use legacy login
legacy_login()Get comprehensive information about the feature flag evaluation:
response = switcher.is_on_with_details('FEATURE_LOGIN_V2')
print(f"Feature enabled: {response.result}") # True or False
print(f"Reason: {response.reason}") # Evaluation reason
print(f"Metadata: {response.metadata}") # Additional contextLoad validation data separately, useful for complex applications:
# Prepare the validation context
switcher.check_value('USER_123').prepare('USER_FEATURE')
# Execute when ready
if switcher.is_on():
enable_user_feature()Chain multiple validation strategies for comprehensive feature control:
# Validate user, network, and other criteria in one call
is_enabled = switcher.check_value('premium_user') \
.check_network('192.168.1.0/24') \
.is_on('PREMIUM_FEATURES')
if is_enabled:
show_premium_dashboard()Subscribe to error notifications for robust error management:
# Set up error handling
Client.subscribe_notify_error(lambda error: print(f"Switcher Error: {error}"))The following features are currently in development:
# π§ TODO: Zero-latency async execution
switcher.throttle(1000).is_on('FEATURE01')# π§ TODO: Force remote resolution for specific features
switcher.remote().is_on('FEATURE01')Load configuration snapshots from the API for local/offline usage:
# Download and save snapshot from API
Client.load_snapshot()Check your current snapshot version:
# Verify snapshot version
version_info = Client.check_snapshot()
print(f"Current snapshot version: {Client.snapshot_version()}")Schedule automatic snapshot updates for zero-latency local mode:
Client.schedule_snapshot_auto_update(
interval=60,
callback=lambda error, updated: (
print(f"Snapshot updated to version: {Client.snapshot_version()}") if updated else None
)
)# π§ TODO: Watch for snapshot file changes
Client.watch_snapshot({
'success': lambda: print('In-memory snapshot updated'),
'reject': lambda err: print(f'Update failed: {err}')
})π§ Note: The mocking features are currently under development
The SDK will include powerful mocking capabilities for testing:
# π§ TODO: Mock feature states for testing
Client.assume('FEATURE01').true()
assert switcher.is_on('FEATURE01') == True
Client.forget('FEATURE01') # Reset to normal behavior
# π§ TODO: Mock with metadata
Client.assume('FEATURE01').false().with_metadata({
'message': 'Feature is disabled'
})
response = switcher.is_on_with_details('FEATURE01')
assert response.result == False
assert response.metadata['message'] == 'Feature is disabled'# π§ TODO: Enable test mode to prevent file locking
Client.enable_test_mode()Validate your feature flag configuration before deployment:
# Verify that all required switchers are configured
try:
Client.check_switchers(['FEATURE_LOGIN', 'FEATURE_DASHBOARD', 'FEATURE_PAYMENTS'])
print("β
All switchers are properly configured")
except Exception as e:
print(f"β Configuration error: {e}")This validation helps prevent deployment issues by ensuring all required feature flags are properly set up in your Switcher domain.
We welcome contributions to the Switcher Client SDK for Python! If you have suggestions, improvements, or bug fixes, please follow these steps:
- Fork the repository.
- Create a new branch for your feature or bug fix.
- Make your changes and commit them with clear messages.
- Submit a pull request detailing your changes and the problem they solve.
Thank you for helping us improve the Switcher Client SDK!
- Python 3.9 or higher
- Virtualenv -
pip install virtualenv - Create a virtual environment -
python3 -m venv .venv - Install Pipenv -
pip install pipenv - Check Makefile for all available commands
