Crossbar.io:如何使用Django服务发布关于主题的消息?

Jor*_*aza 2 python django twisted autobahn crossbar

我刚开始使用Crossbar.io来实现实时统计页面.我看了很多代码示例,但我无法弄清楚如何执行此操作:

我有一个Django的服务(为避免混淆,你可以假设I'm谈论views.py功能),我想它在一个特定的主题发布消息,每当它被调用.我见过这些方法:(1)扩展ApplicationSession和(2)使用"runned"的Application实例.

它们都不适合我,因为Django服务不在一个类中,也不是作为一个独立的python文件执行,所以我找不到一种方法来调用"发布"方法(即我唯一想在服务器端做的事情).

我试图让"StatsBackend",延伸ApplicationSession的实例,并发布一些信息,但StatsBackend._instance是无总是(甚至当我执行"横梁开始"和StatsBackend.INIT()被调用).

StatsBackend.py:

from twisted.internet.defer import inlineCallbacks
from autobahn import wamp
from autobahn.twisted.wamp import ApplicationSession

class StatsBackend(ApplicationSession):

    _instance = None

    def __init__(self, config):
        ApplicationSession.__init__(self, config)
        StatsBackend._instance = self

    @classmethod
    def update_stats(cls, amount):
        if cls._instance:
            cls._instance.publish('com.xxx.statsupdate', {'amount': amount})

    @inlineCallbacks
    def onJoin(self, details):
        res = yield self.register(self)
        print("CampaignStatsBackend: {} procedures registered!".format(len(res)))
Run Code Online (Sandbox Code Playgroud)

test.py:

import StatsBackend

StatsBackend.update_stats(100) #Doesn't do anything, StatsBackend._instance is None
Run Code Online (Sandbox Code Playgroud)

obe*_*tet 6

Django是一个阻塞的WSGI应用程序,它与AutobahnPython不能很好地融合,后者是非阻塞的(在Twisted或asyncio之上运行).

但是,Crossbar.io有一个内置的REST桥,它包含一个HTTP Pusher,您可以通过任何支持HTTP/POST的客户端向其提交事件.Crossbar.io会将这些事件转发给常规的WAMP订阅者(例如,通过WebSocket实时).

Crossbar.io还附带了一个完整的应用程序模板来演示上述功能.尝试:

cd ~/test1
crossbar init --template pusher
crossbar start
Run Code Online (Sandbox Code Playgroud)

打开浏览器http://localhost:8080(打开JS控制台)和第二个终端

curl -H "Content-Type: application/json" \
   -d '{"topic": "com.myapp.topic1", "args": ["Hello, world"]}' \
   http://127.0.0.1:8080/push
Run Code Online (Sandbox Code Playgroud)

然后,您可以在Django等阻止应用程序中进行发布.