【发布时间】:2018-01-12 01:08:46
【问题描述】:
我一直试图让这个脚本以书面顺序执行hub() 中的代码。
hub() 包含标准 Python 代码和使用 Twisted 和 Crossbar 执行 I/O 的请求。
但是,由于 Python 代码是阻塞的,reactor 没有任何机会执行那些“发布”任务。 我的前端在最后收到所有发布的消息。
- 此代码是我实际处理的代码的大幅简化版本。真正的脚本(
hub()和它调用的其他方法)超过 1500 行。修改所有这些函数以使其成为非阻塞的并不理想。如果可以解决此问题,我宁愿将更改隔离到publish()等几个方法。 - 我玩过
async、await、deferLater、loopingCall等术语。我还没有找到对我的情况有帮助的例子。
有没有办法修改publish()(或hub()),让它们按顺序发送消息?
from autobahn.twisted.component import Component, run
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet import reactor, defer
component = Component(
transports=[
{
u"type": u"websocket",
u"url": u"ws://127.0.0.1:8080/ws",
u"endpoint": {
u"type": u"tcp",
u"host": u"localhost",
u"port": 8080,
},
u"options": {
u"open_handshake_timeout": 100,
}
},
],
realm=u"realm1",
)
@component.on_join
@inlineCallbacks
def join(session, details):
print("joined {}: {}".format(session, details))
def publish(context='output', value='default'):
""" Publish a message. """
print('publish', value)
session.publish(u'com.myapp.universal_feedback', {"id": context, "value": value})
def hub(thing):
""" Main script. """
do_things
publish('output', 'some data for you')
do_more_things
publish('status', 'a progress message')
do_even_more_things
publish('status', 'some more data')
do_all_the_things
publish('other', 'something else')
try:
yield session.register(hub, u'com.myapp.hello')
print("procedure registered")
except Exception as e:
print("could not register procedure: {0}".format(e))
if __name__ == "__main__":
run([component])
reactor.run()
【问题讨论】:
标签: wamp twisted autobahn twisted.internet crossbar