A microservices framework for Python that lets service developers concentrate on application logic and encourages testability
npx @tessl/cli install tessl/pypi-nameko@2.14.0A microservices framework for Python that lets service developers concentrate on application logic and encourages testability. Nameko provides a comprehensive toolkit for building scalable, distributed systems with clean separation of concerns and robust inter-service communication patterns.
pip install namekofrom nameko.rpc import rpc, RpcProxy
from nameko.events import event_handler, EventDispatcher
from nameko.web.handlers import http
from nameko.timer import timer
from nameko.dependency_providers import Configfrom nameko.rpc import rpc, RpcProxy
from nameko.events import event_handler, EventDispatcher
from nameko.web.handlers import http
from nameko.dependency_providers import Config
class GreetingService:
name = "greeting_service"
# Configuration dependency
config = Config()
# RPC method
@rpc
def hello(self, name):
return f"Hello, {name}!"
# HTTP endpoint
@http('GET', '/greet/<string:name>')
def greet_http(self, request, name):
return f"Hello via HTTP, {name}!"
class UserService:
name = "user_service"
# RPC proxy to call other services
greeting_rpc = RpcProxy('greeting_service')
# Event dispatcher
event_dispatcher = EventDispatcher()
@rpc
def create_user(self, user_data):
# Create user logic here
user_id = self._save_user(user_data)
# Dispatch event
self.event_dispatcher('user_created', {'user_id': user_id})
# Call another service
greeting = self.greeting_rpc.hello(user_data['name'])
return {'user_id': user_id, 'greeting': greeting}
# Event handler
@event_handler('user_service', 'user_created')
def send_welcome_email(self, payload):
user_id = payload['user_id']
# Send welcome email logic
print(f"Sending welcome email to user {user_id}")
# Run services
from nameko.runners import run_services
if __name__ == '__main__':
run_services([GreetingService, UserService])Nameko follows a microservices architecture with these key components:
This design enables clean separation of business logic from infrastructure concerns, making services highly testable and maintainable.
Remote procedure call system enabling synchronous inter-service communication with automatic serialization, load balancing, and error handling.
def rpc(fn=None, expected_exceptions=()): ...
class RpcProxy:
def __init__(self, target_service, **options): ...Publish-subscribe event system for asynchronous inter-service communication with reliable message delivery and flexible routing patterns.
def event_handler(source_service, event_type, **kwargs): ...
class EventDispatcher:
def __call__(self, event_type, event_data): ...HTTP server integration providing REST API endpoints with request/response handling, URL routing, and WebSocket support.
def http(method, url, **kwargs): ...
def rpc(*args, **kwargs): ... # WebSocket RPC decorator
class WebSocketHubProvider: ...Tools for running services in development and production environments with process management, configuration, and monitoring.
class ServiceRunner:
def __init__(self, config): ...
def add_service(self, service_cls): ...
def start(self): ...
def stop(self): ...
def run_services(services, config=None): ...System for providing services with access to external resources like databases, configuration, and other services through clean dependency injection patterns.
class Config:
def __init__(self, key=None): ...
class DependencyProvider:
def get_dependency(self, worker_ctx): ...Comprehensive testing utilities for unit testing services, mocking dependencies, and integration testing with real message brokers.
def worker_factory(service_cls, **dependencies): ...
def entrypoint_hook(container, method_name): ...
def entrypoint_waiter(container, method_name, timeout=None): ...
def replace_dependencies(container, **dependencies): ...Client libraries for interacting with nameko services from non-nameko applications, supporting both RPC calls and event publishing.
class ServiceRpcProxy:
def __init__(self, service_name, config): ...
class ClusterRpcProxy:
def __init__(self, config): ...
def event_dispatcher(config): ...Built-in timer decorator for running periodic tasks and scheduled operations within services.
def timer(interval): ...Command-line interface for running, managing, and interacting with nameko services in development and production environments.
# Main CLI commands
nameko run <module>[:<ServiceClass>] # Run services
nameko shell # Interactive shell
nameko show-config # Display configuration
nameko backdoor # Debug server# Base Exception Classes
class NamekoException(Exception):
"""Base exception class for nameko framework"""
class BadRequest(NamekoException):
"""Base class for client request errors"""
class ConfigurationError(NamekoException):
"""Raised when there are configuration issues"""
class CommandError(NamekoException):
"""Raised when CLI commands fail"""
# RPC Exceptions
class RemoteError(NamekoException):
"""
Exception representing errors from remote service calls.
Attributes:
- exc_type: Original exception type name
- exc_args: Original exception arguments
- exc_path: Service path where exception occurred
"""
class RpcTimeout(NamekoException):
"""Raised when RPC call times out"""
class UnknownService(NamekoException):
"""Raised when target service cannot be found"""
class ServiceNotFound(NamekoException):
"""Alias for UnknownService - raised when target service cannot be found"""
class MethodNotFound(NamekoException):
"""Raised when target method is not found on service"""
class MalformedRequest(BadRequest):
"""Raised when RPC request format is invalid"""
class IncorrectSignature(BadRequest):
"""Raised when method signature doesn't match call arguments"""
class UnserializableValueError(NamekoException):
"""
Raised when a value cannot be serialized for transport.
Attributes:
- value: The unserializable value
"""
# Container and Extension Exceptions
class ContainerBeingKilled(NamekoException):
"""Raised when container is shutting down"""
class ExtensionNotFound(NamekoException):
"""Raised when required extension cannot be found"""
# Event System Exceptions
class EventHandlerConfigurationError(NamekoException):
"""Raised when event handler is misconfigured"""
# WebSocket Exceptions
class ConnectionNotFound(NamekoException):
"""
Raised when WebSocket connection cannot be found.
Attributes:
- socket_id: The unknown socket identifier
"""
# Testing Exceptions
class EntrypointWaiterTimeout(NamekoException):
"""Raised when entrypoint waiter times out"""
# Base Extension Classes
class Extension:
"""
Base class for all nameko extensions.
Methods:
- setup(): Initialize extension
- start(): Start extension
- stop(): Gracefully stop extension
- kill(): Force stop extension
"""
class Entrypoint(Extension):
"""
Base class for service entrypoints.
Entrypoints define how services can be invoked (RPC, HTTP, events, etc.)
"""
class DependencyProvider(Extension):
"""
Base class for dependency providers.
Methods:
- get_dependency(worker_ctx): Return dependency for service method
- worker_setup(worker_ctx): Setup worker-specific resources
- worker_teardown(worker_ctx): Cleanup worker resources
"""
class SharedExtension(Extension):
"""Base class for extensions shared across multiple services"""
class ProviderCollector:
"""Mixin for collecting and managing dependency providers"""
# Serialization Functions
def serialize(exc):
"""
Serialize exception for transport.
Parameters:
- exc: Exception instance to serialize
Returns:
Serialized exception data
"""
def deserialize(data):
"""
Deserialize exception from transport data.
Parameters:
- data: Serialized exception data
Returns:
Exception instance
"""