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.00
# Nameko
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: nameko
7
- **Language**: Python
8
- **Installation**: `pip install nameko`
9
10
## Core Imports
11
12
```python
13
from nameko.rpc import rpc, RpcProxy
14
from nameko.events import event_handler, EventDispatcher
15
from nameko.web.handlers import http
16
from nameko.timer import timer
17
from nameko.dependency_providers import Config
18
```
19
20
## Basic Usage
21
22
```python
23
from nameko.rpc import rpc, RpcProxy
24
from nameko.events import event_handler, EventDispatcher
25
from nameko.web.handlers import http
26
from nameko.dependency_providers import Config
27
28
class GreetingService:
29
name = "greeting_service"
30
31
# Configuration dependency
32
config = Config()
33
34
# RPC method
35
@rpc
36
def hello(self, name):
37
return f"Hello, {name}!"
38
39
# HTTP endpoint
40
@http('GET', '/greet/<string:name>')
41
def greet_http(self, request, name):
42
return f"Hello via HTTP, {name}!"
43
44
class UserService:
45
name = "user_service"
46
47
# RPC proxy to call other services
48
greeting_rpc = RpcProxy('greeting_service')
49
50
# Event dispatcher
51
event_dispatcher = EventDispatcher()
52
53
@rpc
54
def create_user(self, user_data):
55
# Create user logic here
56
user_id = self._save_user(user_data)
57
58
# Dispatch event
59
self.event_dispatcher('user_created', {'user_id': user_id})
60
61
# Call another service
62
greeting = self.greeting_rpc.hello(user_data['name'])
63
64
return {'user_id': user_id, 'greeting': greeting}
65
66
# Event handler
67
@event_handler('user_service', 'user_created')
68
def send_welcome_email(self, payload):
69
user_id = payload['user_id']
70
# Send welcome email logic
71
print(f"Sending welcome email to user {user_id}")
72
73
# Run services
74
from nameko.runners import run_services
75
76
if __name__ == '__main__':
77
run_services([GreetingService, UserService])
78
```
79
80
## Architecture
81
82
Nameko follows a microservices architecture with these key components:
83
84
- **Services**: Python classes that encapsulate business logic and expose functionality through entrypoints
85
- **Entrypoints**: Decorators (@rpc, @http, @event_handler, @timer) that define how services can be called
86
- **Dependency Providers**: Objects that provide services with access to external resources (databases, APIs, config)
87
- **Extensions**: The underlying framework components that handle messaging, routing, and service lifecycle
88
- **Runners**: Components that manage service startup, worker processes, and graceful shutdown
89
90
This design enables clean separation of business logic from infrastructure concerns, making services highly testable and maintainable.
91
92
## Capabilities
93
94
### RPC Communication
95
96
Remote procedure call system enabling synchronous inter-service communication with automatic serialization, load balancing, and error handling.
97
98
```python { .api }
99
def rpc(fn=None, expected_exceptions=()): ...
100
101
class RpcProxy:
102
def __init__(self, target_service, **options): ...
103
```
104
105
[RPC Communication](./rpc-communication.md)
106
107
### Event System
108
109
Publish-subscribe event system for asynchronous inter-service communication with reliable message delivery and flexible routing patterns.
110
111
```python { .api }
112
def event_handler(source_service, event_type, **kwargs): ...
113
114
class EventDispatcher:
115
def __call__(self, event_type, event_data): ...
116
```
117
118
[Event System](./event-system.md)
119
120
### HTTP Interface
121
122
HTTP server integration providing REST API endpoints with request/response handling, URL routing, and WebSocket support.
123
124
```python { .api }
125
def http(method, url, **kwargs): ...
126
127
def rpc(*args, **kwargs): ... # WebSocket RPC decorator
128
129
class WebSocketHubProvider: ...
130
```
131
132
[HTTP Interface](./http-interface.md)
133
134
### Service Management
135
136
Tools for running services in development and production environments with process management, configuration, and monitoring.
137
138
```python { .api }
139
class ServiceRunner:
140
def __init__(self, config): ...
141
def add_service(self, service_cls): ...
142
def start(self): ...
143
def stop(self): ...
144
145
def run_services(services, config=None): ...
146
```
147
148
[Service Management](./service-management.md)
149
150
### Dependency Injection
151
152
System for providing services with access to external resources like databases, configuration, and other services through clean dependency injection patterns.
153
154
```python { .api }
155
class Config:
156
def __init__(self, key=None): ...
157
158
class DependencyProvider:
159
def get_dependency(self, worker_ctx): ...
160
```
161
162
[Dependency Injection](./dependency-injection.md)
163
164
### Testing Framework
165
166
Comprehensive testing utilities for unit testing services, mocking dependencies, and integration testing with real message brokers.
167
168
```python { .api }
169
def worker_factory(service_cls, **dependencies): ...
170
171
def entrypoint_hook(container, method_name): ...
172
173
def entrypoint_waiter(container, method_name, timeout=None): ...
174
175
def replace_dependencies(container, **dependencies): ...
176
```
177
178
[Testing Framework](./testing-framework.md)
179
180
### Standalone Clients
181
182
Client libraries for interacting with nameko services from non-nameko applications, supporting both RPC calls and event publishing.
183
184
```python { .api }
185
class ServiceRpcProxy:
186
def __init__(self, service_name, config): ...
187
188
class ClusterRpcProxy:
189
def __init__(self, config): ...
190
191
def event_dispatcher(config): ...
192
```
193
194
[Standalone Clients](./standalone-clients.md)
195
196
### Timer and Scheduling
197
198
Built-in timer decorator for running periodic tasks and scheduled operations within services.
199
200
```python { .api }
201
def timer(interval): ...
202
```
203
204
[Timer and Scheduling](./timer-scheduling.md)
205
206
### CLI Interface
207
208
Command-line interface for running, managing, and interacting with nameko services in development and production environments.
209
210
```python { .api }
211
# Main CLI commands
212
nameko run <module>[:<ServiceClass>] # Run services
213
nameko shell # Interactive shell
214
nameko show-config # Display configuration
215
nameko backdoor # Debug server
216
```
217
218
[CLI Interface](./cli-interface.md)
219
220
## Common Types
221
222
```python { .api }
223
# Base Exception Classes
224
class NamekoException(Exception):
225
"""Base exception class for nameko framework"""
226
227
class BadRequest(NamekoException):
228
"""Base class for client request errors"""
229
230
class ConfigurationError(NamekoException):
231
"""Raised when there are configuration issues"""
232
233
class CommandError(NamekoException):
234
"""Raised when CLI commands fail"""
235
236
# RPC Exceptions
237
class RemoteError(NamekoException):
238
"""
239
Exception representing errors from remote service calls.
240
241
Attributes:
242
- exc_type: Original exception type name
243
- exc_args: Original exception arguments
244
- exc_path: Service path where exception occurred
245
"""
246
247
class RpcTimeout(NamekoException):
248
"""Raised when RPC call times out"""
249
250
class UnknownService(NamekoException):
251
"""Raised when target service cannot be found"""
252
253
class ServiceNotFound(NamekoException):
254
"""Alias for UnknownService - raised when target service cannot be found"""
255
256
class MethodNotFound(NamekoException):
257
"""Raised when target method is not found on service"""
258
259
class MalformedRequest(BadRequest):
260
"""Raised when RPC request format is invalid"""
261
262
class IncorrectSignature(BadRequest):
263
"""Raised when method signature doesn't match call arguments"""
264
265
class UnserializableValueError(NamekoException):
266
"""
267
Raised when a value cannot be serialized for transport.
268
269
Attributes:
270
- value: The unserializable value
271
"""
272
273
# Container and Extension Exceptions
274
class ContainerBeingKilled(NamekoException):
275
"""Raised when container is shutting down"""
276
277
class ExtensionNotFound(NamekoException):
278
"""Raised when required extension cannot be found"""
279
280
# Event System Exceptions
281
class EventHandlerConfigurationError(NamekoException):
282
"""Raised when event handler is misconfigured"""
283
284
# WebSocket Exceptions
285
class ConnectionNotFound(NamekoException):
286
"""
287
Raised when WebSocket connection cannot be found.
288
289
Attributes:
290
- socket_id: The unknown socket identifier
291
"""
292
293
# Testing Exceptions
294
class EntrypointWaiterTimeout(NamekoException):
295
"""Raised when entrypoint waiter times out"""
296
297
# Base Extension Classes
298
class Extension:
299
"""
300
Base class for all nameko extensions.
301
302
Methods:
303
- setup(): Initialize extension
304
- start(): Start extension
305
- stop(): Gracefully stop extension
306
- kill(): Force stop extension
307
"""
308
309
class Entrypoint(Extension):
310
"""
311
Base class for service entrypoints.
312
313
Entrypoints define how services can be invoked (RPC, HTTP, events, etc.)
314
"""
315
316
class DependencyProvider(Extension):
317
"""
318
Base class for dependency providers.
319
320
Methods:
321
- get_dependency(worker_ctx): Return dependency for service method
322
- worker_setup(worker_ctx): Setup worker-specific resources
323
- worker_teardown(worker_ctx): Cleanup worker resources
324
"""
325
326
class SharedExtension(Extension):
327
"""Base class for extensions shared across multiple services"""
328
329
class ProviderCollector:
330
"""Mixin for collecting and managing dependency providers"""
331
332
# Serialization Functions
333
def serialize(exc):
334
"""
335
Serialize exception for transport.
336
337
Parameters:
338
- exc: Exception instance to serialize
339
340
Returns:
341
Serialized exception data
342
"""
343
344
def deserialize(data):
345
"""
346
Deserialize exception from transport data.
347
348
Parameters:
349
- data: Serialized exception data
350
351
Returns:
352
Exception instance
353
"""
354
```