横杆io:如何使用Django服务发布主题消息?

2024-10-01 09:33:37 发布

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

我刚开始用横杆io实现实时统计页面。我看过很多代码示例,但我不知道如何做到这一点:

我有一个Django服务(为了避免混淆,您可以假设我所说的是视图.py)我希望它能在一个特定的主题中发布消息,无论何时被调用。我见过这些方法:(1)Extending ApplicationSession和(2)using an Application instance that is "runned"。在

它们都不适合我,因为Django服务不在类中,也不作为独立的python文件执行,所以我找不到调用“publish”方法的方法(这是我在服务器端唯一想做的事情)。在

我试图获取一个“StatsBackend”的实例,它扩展了ApplicationSession,并发布了一些东西。。。但是StatsBackend.\u实例始终是None(即使在我执行'crossbar start'和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)))

在测试.py公司名称:

^{pr2}$

Tags: django实例方法instancefrompyimportself
2条回答

我找到了我需要的东西:可以执行httppost请求来发布主题。在

您可以阅读文档了解更多信息:https://github.com/crossbario/crossbar/wiki/Using-the-REST-to-WebSocket-Pusher

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

但是,横杆io有一个内置的REST桥,它包括一个HTTP Pusher,您可以通过任何支持HTTP/POST的客户端向其提交事件。横杆io将这些事件转发给普通WAMP订户(如通过WebSocket实时)。在

在横杆io还提供了一个完整的应用程序模板来演示上述功能。尝试:

cd ~/test1
crossbar init  template pusher
crossbar start

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

^{pr2}$

然后,可以从Django这样的阻塞应用程序中进行发布。在

相关问题 更多 >