WAMP和Django应用程序使用Python2.7和3.4有可能吗?

2024-03-29 02:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我们希望如何使用WAMP:这个程序有一个Javascript前端和Python/Django后端。我们要做的一件事是,当单击前端的按钮时,在后端启动一个函数。但这有时会花费太多时间,因此我们允许用户通过单击另一个按钮来取消。这个函数进行远程过程调用,这将导致函数提前停止(它更改在函数中检查的变量)。将来可能还需要RPC或Pub/Sub。你知道吗

我们使用autobahn_sync模块让它与Python2.7一起工作,但它使用的是Twisted,Twisted还没有完全移植到Python3.x。这就是为什么我们需要另一种方法来获得WAMP通知才能在3.x上工作

asyncio是受支持的,从crossbar documentation看来它可以用来代替Twisted,但是如果不阻止应该并行运行的代码,我们就无法让它工作(下面添加了代码)。而且似乎没有什么东西像使用asyncio而不是Twisted的autobahn\u同步。你知道吗

我们是新来的,可能还缺什么。你知道吗

下面是我们使用asyncio测试的代码(使用python3.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")

我们如何注册到主题并从主题返回跑步者。跑步打电话?在Python 2.7测试中,使用autobahn\u 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

Tags: 函数run代码fromselfloopeventregister