使用Python 2.7和3.4的Django App WAMP - 是否可能?

时间:2016-05-09 11:39:48

标签: python twisted autobahn crossbar wamp-protocol

问题的实质是:是否可以在支持Python 2.7和3.4的Django应用程序中使用WAMP通知,考虑到代码应该运行并且只有在进行远程过程调用时才会被中断? (也就是说,它不仅等待RPC的到来)

我们如何使用WAMP:该程序有一个带有Python / Django后端的Javascript前端。我们所做的一件事是在点击前端的按钮时在后端启动一个功能。这有时会花费太多时间,因此我们允许用户通过单击另一个按钮取消该操作。这个进行远程过程调用,这将导致函数提前停止(它更改在函数中检查的变量)。将来可能还有对RPC或Pub / Sub的其他需求。

我们使用autobahn_sync模块使用Python 2.7,但它使用Twisted,但尚未完全移植到Python 3.x.这就是为什么我们需要另一种方式让我们的WAMP通知在3.x上工作。

支持asyncio,并且crossbar documentation似乎可以使用它而不是Twisted,但我们无法在不阻塞应该并行运行的代码的情况下使用它(代码在下面添加)。并且似乎没有使用asyncio而不是Twisted的autobahn_sync。

我们是WAMP的新手,可能会有一些我们遗漏的东西。

这是我们使用asyncio进行测试的代码(使用Python 3.4)。它阻止了函数的其余部分:

from asyncio import coroutine, new_event_loop, set_event_loop
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner

class MyComponent(ApplicationSession):
        @wamp.register("com.function.cancel")
        def cancel(self):
            print("called cancel procedure")
            # do things here
            return "Canceled"

        @coroutine
        def onJoin(self, details):
            res = yield from self.register(self)
            print("{} procedures registered.".format(len(res)))

def function_triggered_in_frontend():
    loop = new_event_loop()
    set_event_loop(loop)
    runner = ApplicationRunner(url=u"ws://localhost:8080/ws", realm=u"realm1")
    runner.run(MyComponent)
    # and now the function should continue working on other things, but does't because it doesn't return from runner.run().
    print("do stuff")

我们如何注册主题并从runner.run调用返回?在Python 2.7测试中,使用autobahn_sync我们可以简单地执行:

from autobahn_sync import register, run, AlreadyRunningError
@register('com.function.cancel')
def cancel_generate_jobs():
    print("called cancel procedure")
    @register('com.function.cancel')
    # def cancel_generate_jobs():

def function_triggered_in_frontend():
    try:
        run(realm=u"realm1")
    except AlreadyRunningError:
        logger.info('AutbahnSync instance already started.')
    # and then the code would continue being processed here, as we want

0 个答案:

没有答案