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

标签 python twisted

是否存在用于将进程内服务消息传递给另一个服务的扭曲机制?我写了一个原型(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

关于python - Twisted 的服务间消息传递/总线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6999812/

相关文章:

python - 当您的数据不是均匀时间间隔时,是否有一种快速方法可以以均匀时间间隔对 Pandas Dataframe 进行滚动求和?

Python Matplotlib 更新散点图

python - Django MVT 设计 : Should I have all the code in models or views?

python - 扭曲的客户端内存泄漏

python 扭曲 : "wait" for a variable to be filled by another event

python - 根据断点创建更大范围的子范围

python - 具有概率估计的增量 SVM

python - scrapy 具有多个帐户或使用不同的帐户重新登录(不同的 cookie)

python - 导入时找不到twisted.web

python - 在 Twisted 回调中使用 async/await 语法