我正在尝试在Django中进行ZeroMQ PUSH-PULL事件管理。基于this link,我将创建一个PUSH客户端:
context = zmq.Context()
zmq_socket = context.socket(zmq.PUSH)
zmq_socket.connect("tcp://127.0.0.1:5557")
for num in xrange(20000):
work_message = { 'num' : num }
zmq_socket.send_json(work_message)
和PULL服务器:
context = zmq.Context()
consumer_receiver = context.socket(zmq.PULL)
consumer_receiver.bind("tcp://127.0.0.1:5557")
work = consumer_receiver.recv_json()
data = work['num']
print data
在单独的文件中实现PUSH / PULL工作正常。但我想在Django视图中使用PULL服务器功能。也就是说,每当收到消息时,我希望它能在Django上接收,我可以操作Django ORM。我该如何处理?谢谢。
答案 0 :(得分:1)
不确定您是否询问如何在使用ZMQ的脚本中包含Django,但这是我如何做到的(使用virtualenv)
#!/usr/bin/python2.7
import sys
import os
PATH=os.path.abspath(os.path.dirname(__file__))
# Relative path to the virtual environment
# (relative to the stand-alone script)
rel_path = '../../bin/activate_this.py'
activate_this = os.path.join(PATH, rel_path)
# this is needed to read the settings:
sys.path.append("../")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mainapp.settings")
execfile(activate_this, dict(__file__=activate_this))
import zmq
import json
from django.conf import settings
import django
django.setup()
from .models import Mymodel
port = "5556"
context = zmq.Context()
print "Connecting to server..."
socket = context.socket(zmq.REQ)
socket.connect ("tcp://localhost:%s" % port)
while True:
#this will listen and wait for a message
mymessage = json.loads(socket.recv())
try:
#do stuff
my = Mymodel.objects.get(id=mymessage['id'])
#send something back
socket.send("1")
except:
#on error
socket.send("0")