Skip to main content
 首页 » 编程设计

python之Twisted 的服务间消息传递/总线

2025年05月04日11oomusou

是否存在用于将进程内服务消息传递给另一个服务的扭曲机制?我写了一个原型(prototype)总线,看起来像

    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) 

像这样使用

foo.py

from Application.data import bus 
 
def doSomething(fooArg): 
    print "Hello from Foo, you sent " , fooArg 
 
bus.register("foo.doSomething", doSomething) 

酒吧.py

 from Application.data import bus 
 
 bus.call("foo.doSomething", "A simple string") 

这是一个非常简单的示例,因为主要用例是共享内存中的公共(public)数据存储。最初我尝试使用单例,但在尝试用单元测试覆盖它时遇到了太多问题。然后,我尝试在所有地方传递对数据存储的引用,但感觉我将我的应用程序绑定(bind)到 100% 依赖于数据存储,永远不会改变。

我对 data.bus 想法的唯一担心是它基本上只是一个过度美化的全局变量。所以我的问题是,twisted 内部是否存在某种服务总线或消息传递系统以允许在 twisted 应用程序内部的不同资源之间传递任意消息,或者我的 data.bus 想法是否与解决方案一样好?

请您参考如下方法:

听起来你想要 python 的“黑板”或“元组空间”(我不明白扭曲如何改变事物?)?如果是这样,这是一个 - http://pypi.python.org/pypi/linda/0.5.1