繁体   English   中英

结合使用装饰器方法和Aut​​obahnWS,如何发布与订阅回调及其会话引用无关的消息?

[英]Using the Decorator approach with AutobahnWS, how to publish messages independent from subscription callbacks and it's Session-Reference?

在使用Subclassing-Approach之前,当我与Autobahn和WAMP一起工作时,偶然发现了装饰器/函数方法,而我实际上更喜欢装饰器/函数方法。

然而。 我有一个从外部硬件(通过回调)调用的函数,该函数每次被调用时都需要发布到Crossbar.io Router。

这就是我这样做的方式,在on_join -> async def joined(session, details)之后on_join -> async def joined(session, details)保留Session的引用。

from autobahn.asyncio.component import Component
from autobahn.asyncio.component import run

global_session = None

comp = Component(
    transports=u"ws://localhost:8080/ws",
    realm=u"realm1",
)

def callback_from_hardware(msg):
    if global_session is None:
        return
    global_session.publish(u'com.someapp.somechannel', msg)

@comp.on_join
async def joined(session, details):
    global global_session
    global_session = session
    print("session ready")

if __name__ == "__main__":
    run([comp])

但是,这种在组件已加入连接后保持引用的方法感觉有些“奇怪”。 有其他方法吗? 可以通过其他方式完成此操作吗?

如果不是这样的话,那么子类化和让所有应用程序依赖该子类中的代码的感觉会更“正确”(但是将我的应用程序的所有内容都保留在一个子类中也感觉很奇怪)。

我建议使用异步队列而不是共享会话:

import asyncio

from autobahn.asyncio.component import Component
from autobahn.asyncio.component import run

queue = asyncio.queues.Queue()

comp = Component(
    transports=u"ws://localhost:8080/ws",
    realm=u"realm1",
)


def callback_from_hardware(msg):
    queue.put_nowait((u'com.someapp.somechannel', msg,))


@comp.on_join
async def joined(session, details):
    print("session ready")

    while True:
        topic, message, = await queue.get()
        print("Publishing: topic: `%s`, message: `%s`" % (topic, message))
        session.publish(topic, message)


if __name__ == "__main__":
    callback_from_hardware("dassdasdasd")
    run([comp])

尽管最简单的IMO是使用Crossbar的http桥,但您可以在此处采用多种方法。 因此,只要从您的硬件收到事件回调,您就可以向Crossbar发出http POST请求,您的消息就会被传递

有关http桥https://crossbar.io/docs/HTTP-Bridge-Publisher/的更多详细信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM