Reputation: 18261
Is there an in-twisted mechanism for passing messages in-process service to another? I wrote up a prototype bus that looks like
from collections import defaultdict
channels = defaultdict(list)
def registerSingle(name, callback):
"""
Similar to register but ensures only one callback is register to a channel
@todo change Exception to something more appropriate
:name str A reasonably coherent name for a callback channel
:callback callable Either a bound method or just a function
"""
global channels
if len(channels[name]) > 0:
raise Exception("Tried to register %s but already has %s registered" % ( name, channels) )
channels[name].append(callback)
def register(name, callback):
"""
Binds a callback to a named channel
:name str A reasonably coherent name for a callback channel
:callback callable Either a bound method or just a function
"""
global channels
channels[name].append(callback)
def call(name, *args, **kwargs):
"""
Applies the provided arguments to any and all callbacks for a specified channel
:name str A reasonably coherent name for a callback channel
"""
for callback in channels[name]:
callback(*args, **kwargs)
To be used like
foo.py
from Application.data import bus
def doSomething(fooArg):
print "Hello from Foo, you sent " , fooArg
bus.register("foo.doSomething", doSomething)
bar.py
from Application.data import bus
bus.call("foo.doSomething", "A simple string")
That's a really simple example as the primary use case is to share a common in memory data store. Initially I tried using a singleton but ran into too many problems when trying to cover it with unit-tests. I then tried passing a reference to the data store everywhere but felt that I was tying my application up to be 100% dependent on the data store never changing.
My only concern with the data.bus idea is that it's basically just an over glorified global variable. So my question, is there some sort of service bus or messaging system inside of twisted to allow for passing arbitrary messages between different resources inside of a twisted application or is my data.bus idea as good as it gets for a solution?
Upvotes: 2
Views: 375
Reputation: 46862
it sounds like you want a "blackboard" or "tuple space" for python (i don't see how twisted changes things?)? if so, here's one - http://pypi.python.org/pypi/linda/0.5.1
Upvotes: 1