-
Notifications
You must be signed in to change notification settings - Fork 10
/
mqModel.py
47 lines (37 loc) · 1.39 KB
/
mqModel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import cherrypy
import json
from django.db import models
from ws4py.messaging import TextMessage
from domoweb.exceptions import MQNoResponseError
# MQ
import zmq
from mq.pubsub.subscriber import MQAsyncSub
from mq.reqrep.client import MQSyncReq
from mq.message import MQMessage
class MQModel(models.Model):
class Meta:
abstract = True # Prevent the table to be created with syncdb
@classmethod
def get_req(cls, id, data=None):
_data = cls._sync_req_rep(id, data)
result = json.loads(_data[1])
return result
@classmethod
def _sync_req_rep(cls, msgid, data=None):
cli = MQSyncReq(zmq.Context())
msg = MQMessage(msgid, data)
cherrypy.log("MQ sync REQ : [%s]" % msgid)
request = cli.request('manager', msg.get(), timeout=10)
if not request:
raise MQNoResponseError()
return request.get()
class MQEvent(MQAsyncSub):
def __init__(self, zmqcontext, id, callback, filter):
MQAsyncSub.__init__(self, zmqcontext, 'domoweb-%s' % id, filter)
self.callback = callback
cherrypy.log("MQ async SUB : %s" % str(filter))
def on_message(self, msgid, content):
cherrypy.log("QM New pub message : [%s]" % msgid)
msg = json.dumps({'id':msgid, 'content':content})
cherrypy.engine.publish('websocket-broadcast', TextMessage(msg))
self.callback(content)