Python Client Integration
This tutorial walks you through integrating the Calimero Python client SDK into your applications, from basic setup to advanced patterns and real-world use cases.
Prerequisites
Before starting this tutorial, ensure you have:
- Python 3.9+ installed
- pipx package manager (recommended) or pip
- Basic Python knowledge (error handling, function calls)
- Calimero node running locally or remotely
- Basic understanding of Calimero concepts (contexts, applications, functions)
Step 1: Installation and Setup
Install the Python Client
pipx install calimero-client-py
pipx ensurepath
Verify Installation
# test_installation.py
import calimero
def test_installation():
"""Test that the Python client is properly installed."""
try:
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
print("✓ Python client installed successfully!")
return True
except Exception as e:
print(f"✗ Installation test failed: {e}")
return False
if __name__ == "__main__":
test_installation()
Run the test:
python test_installation.py
Step 2: Basic Connection and Operations
Create a Connection
# basic_connection.py
import calimero
def basic_connection_example():
"""Basic connection and operation example."""
# Create connection
connection = calimero.create_connection(
api_url="http://localhost:2428",
node_name="example-node"
)
# Create client
client = calimero.create_client(connection)
# Test basic operations
print("Testing basic operations...")
# Get peers count
peers_count = client.get_peers_count()
print(f"Connected peers: {peers_count}")
# List contexts
contexts = client.list_contexts()
print(f"Found {len(contexts)} contexts")
# List applications
apps = client.list_applications()
print(f"Found {len(apps)} applications")
return client
if __name__ == "__main__":
basic_connection_example()
Error Handling
# error_handling.py
import calimero
def error_handling_example():
"""Example of proper error handling."""
try:
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
# This might fail if the context doesn't exist
context = client.get_context("non-existent-context")
print(f"Context: {context}")
except RuntimeError as e:
print(f"Client error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == "__main__":
error_handling_example()
Step 3: Application Management
Install and Manage Applications
# application_management.py
import calimero
def application_management_example():
"""Example of managing applications."""
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
print("=== Application Management Example ===")
# Install an application
print("Installing application...")
app = client.install_application(
url="https://example.com/my-app.wasm",
metadata=b'{"name": "My Test App", "version": "1.0.0"}'
)
app_id = app["application_id"]
print(f"✓ Installed app: {app_id}")
# Get application details
app_info = client.get_application(app_id)
print(f"✓ App details: {app_info}")
# List all applications
apps = client.list_applications()
print(f"✓ Total applications: {len(apps)}")
# Uninstall the application
print("Uninstalling application...")
result = client.uninstall_application(app_id)
print(f"✓ Uninstall result: {result}")
return app_id
if __name__ == "__main__":
application_management_example()
Development Application Installation
# dev_application.py
import calimero
def dev_application_example():
"""Example of installing development applications."""
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
print("=== Development Application Example ===")
# Install development application from local path
app = client.install_dev_application(
path="/path/to/your/app.wasm",
metadata=b'{"name": "Dev App", "version": "0.1.0"}'
)
app_id = app["application_id"]
print(f"✓ Installed dev app: {app_id}")
# Clean up
client.uninstall_application(app_id)
print("✓ Cleaned up dev app")
if __name__ == "__main__":
dev_application_example()
Step 4: Context Management
Create and Manage Contexts
# context_management.py
import calimero
def context_management_example():
"""Example of managing contexts."""
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
print("=== Context Management Example ===")
# First, install an application
print("Installing application...")
app = client.install_application(
url="https://example.com/my-app.wasm",
metadata=b'{"name": "Context Test App"}'
)
app_id = app["application_id"]
try:
# Create a context
print("Creating context...")
context = client.create_context(
application_id=app_id,
protocol="near",
params='{"network": "testnet"}'
)
context_id = context["context_id"]
print(f"✓ Created context: {context_id}")
# Get context details
context_info = client.get_context(context_id)
print(f"✓ Context info: {context_info}")
# Sync the context
print("Syncing context...")
sync_result = client.sync_context(context_id)
print(f"✓ Sync result: {sync_result}")
# Get context identities
identities = client.get_context_identities(context_id)
print(f"✓ Context identities: {identities}")
# Get context storage
storage = client.get_context_storage(context_id)
print(f"✓ Context storage: {storage}")
return context_id
finally:
# Clean up
print("Cleaning up...")
client.delete_context(context_id)
client.uninstall_application(app_id)
print("✓ Cleanup completed")
if __name__ == "__main__":
context_management_example()
Step 5: Function Execution
Execute Smart Contract Functions
# function_execution.py
import calimero
def function_execution_example():
"""Example of executing smart contract functions."""
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
print("=== Function Execution Example ===")
# Install application
app = client.install_application(
url="https://example.com/my-app.wasm",
metadata=b'{"name": "Function Test App"}'
)
app_id = app["application_id"]
try:
# Create context
context = client.create_context(app_id, "near")
context_id = context["context_id"]
print(f"✓ Created context: {context_id}")
# Generate executor identity
executor_identity = client.generate_context_identity()
executor_public_key = executor_identity["public_key"]
print(f"✓ Generated executor identity")
# Execute a simple function
print("Executing function...")
result = client.execute_function(
context_id=context_id,
method="initialize",
args='{}',
executor_public_key=executor_public_key
)
print(f"✓ Function result: {result}")
# Execute function with complex arguments
print("Executing function with arguments...")
transfer_result = client.execute_function(
context_id=context_id,
method="transfer",
args='{"amount": 100, "to": "alice.near", "memo": "Payment"}',
executor_public_key=executor_public_key
)
print(f"✓ Transfer result: {transfer_result}")
return context_id
finally:
# Clean up
client.delete_context(context_id)
client.uninstall_application(app_id)
print("✓ Cleanup completed")
if __name__ == "__main__":
function_execution_example()
Step 6: Best Practices
Connection Management
# connection_management.py
import calimero
class CalimeroClientWrapper:
"""Wrapper class for better connection management."""
def __init__(self, api_url: str, node_name: str = None):
self.connection = calimero.create_connection(api_url, node_name)
self.client = calimero.create_client(self.connection)
def get_connection_info(self):
"""Get connection information."""
return {
"api_url": self.client.get_api_url(),
"peers_count": self.client.get_peers_count()
}
def health_check(self):
"""Perform a health check."""
try:
contexts = self.client.list_contexts()
return {"status": "healthy", "contexts_count": len(contexts)}
except Exception as e:
return {"status": "unhealthy", "error": str(e)}
# Usage example
def connection_management_example():
"""Example of proper connection management."""
wrapper = CalimeroClientWrapper("http://localhost:2428", "my-node")
# Get connection info
info = wrapper.get_connection_info()
print(f"Connection info: {info}")
# Health check
health = wrapper.health_check()
print(f"Health status: {health}")
if __name__ == "__main__":
connection_management_example()
Error Handling Patterns
# error_patterns.py
import calimero
import time
def robust_client_operation(client, operation, *args, max_retries=3, **kwargs):
"""Execute operation with retry logic."""
last_error = None
for attempt in range(max_retries):
try:
return operation(*args, **kwargs)
except RuntimeError as e:
last_error = e
if attempt < max_retries - 1:
print(f"Attempt {attempt + 1} failed, retrying in 2s: {e}")
time.sleep(2)
else:
print(f"All {max_retries} attempts failed")
break
raise last_error
def error_patterns_example():
"""Example of robust error handling patterns."""
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
# Use robust operation wrapper
try:
contexts = robust_client_operation(client, client.list_contexts)
print(f"Successfully retrieved {len(contexts)} contexts")
except RuntimeError as e:
print(f"Failed to retrieve contexts: {e}")
if __name__ == "__main__":
error_patterns_example()
Step 7: Testing
Basic Testing
# test_basic.py
import calimero
def test_basic_operations():
"""Test basic client operations."""
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
# Test connection
api_url = client.get_api_url()
assert api_url == "http://localhost:2428"
# Test peers count
peers = client.get_peers_count()
assert isinstance(peers, (int, dict))
# Test contexts listing
contexts = client.list_contexts()
assert isinstance(contexts, (list, dict))
print("✓ All basic tests passed")
if __name__ == "__main__":
test_basic_operations()
Integration Testing
# test_integration.py
import calimero
def test_full_workflow():
"""Test complete workflow."""
connection = calimero.create_connection("http://localhost:2428")
client = calimero.create_client(connection)
print("=== Integration Test ===")
# Install application
app = client.install_application(
url="https://example.com/test.wasm",
metadata=b'{"name": "Test App"}'
)
app_id = app["application_id"]
print(f"✓ Installed app: {app_id}")
try:
# Create context
context = client.create_context(app_id, "near")
context_id = context["context_id"]
print(f"✓ Created context: {context_id}")
# Generate identity
identity = client.generate_context_identity()
print(f"✓ Generated identity")
# Execute function
result = client.execute_function(
context_id, "test", "{}", identity["public_key"]
)
print(f"✓ Function executed: {result}")
print("✓ Integration test completed successfully")
finally:
# Cleanup
client.delete_context(context_id)
client.uninstall_application(app_id)
print("✓ Cleanup completed")
if __name__ == "__main__":
test_full_workflow()
Resources
- GitHub Repository: calimero-client-py
- PyPI Package: calimero-client-py
- Community Discord: Join the conversation
- Email Support: team@calimero.network
Happy coding with the Calimero Python client! 🐍✨
Was this page helpful?