To share data between a child and a parent process using the multiprocessing interface you may use one of the methods proposed in https://docs.python.org/2/library/multiprocessing.html, for instance a Queue or a Pipe.
Here's what you should do to use a queue to talk to a child process from within a Django web application (I suppose that the background/child process is controlling a single device for all users of the web application, so everybody will get the same results -- this could also be per session):
- Create a global queue object inside your views.py like this
global_q = Queue()
. - Create a view for initializing the process, and pass the global
Queue
to the process function:
def init_process(request): p = Process(target=the_process, args=(global_q, )) p.daemon = True p.start() return HttpResponse(json.dumps('Ok'), content_type="application/json")
- Create a different view that will read from the global Queue:
def read_process_status(request): data = global_q.get() return HttpResponse(json.dumps(data), content_type="application/json")
- Your process function handles the device and write events in the queue parameter when needed:
def the_process(local_q): # do some things local_q.put([6]) # do some other things local_q.put([34])
For the above to work without problems you must check if th queue is empty or make it non-block etc, but you'll get the idea.