4
votes

I am trying to make a ZeroMQ PUSH-PULL event management in Django. Based on this link, I will be creating a PUSH client as :

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)

and a PULL server as:

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

Implementing PUSH/PULL in a separate file works fine. But I want the PULL server functionality in Django views. That is, whenever a message is received, I want it to be received on Django and I can operate Django ORM. How do I handle this? Thanks.

1
Not sure what you're asking.. Do you want to know how to include Django in your script, so you can use the ORM?Alex

1 Answers

2
votes

Not sure if you're asking how to include Django in a script that uses ZMQ, but here is how I do it (using 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")