3

Is there a correct way to start an infinite task from Django Framework? I need to run a MQTT Client (based on Paho) and a Python PID implementation.

I want to use Django as "Orhestrator" because I want to start daemons only if django it's running.

I use django becasue of it's simplicity for creating Rest API and ORM layer.

The only way I've found (here on github) it's to modify the __init__.py including here my external module --> How to use paho mqtt client in django?.

This it's not suitable for me beacause it start the daemons on every django manage task.

Has anyone already solved this problem? Thank you in advance.

Andrea
  • 67
  • 7
  • WSGI applications are designed to be run in a request / response cycle. A WSGI server will usually run many of these cycles in worker threads and processes, which it manages in the sense of creating and disposing them on demand. To have an infinte single task is therefore against the design. You might need to consider a design that has multiple processes with one client instance each running and where a worker including client might get lost at any time. – Klaus D. Oct 07 '18 at 10:30
  • Then maybe Django it's not the right framework for my needs. – Andrea Oct 07 '18 at 14:13

1 Answers1

1

As far as I am concerned, I use supervisor to daemonize my django management commands.

As my django projects all run in a virtualenv, I created a script to initialize the virtualenv before running the management command:

/home/cocoonr/run_standalone.sh

#/bin/bash
export WORKON_HOME=/usr/share/virtualenvs
source /usr/share/virtualenvwrapper/virtualenvwrapper.sh
workon cocoonr  # name of my virtualenv

django-admin "$@"

And here is an exemple of supervisor configuration for a command

/etc/supervisor/conf.d/cocoonr.conf

[program:send_queued_mails_worker]
command=/bin/bash /home/cocoonr/run_standalone.sh send_queued_mails_worker
user=cocoonr
group=cocoonr
stopasgroup=true
environment=LANG=fr_FR.UTF-8,LC_ALL=fr_FR.UTF-8
stderr_logfile=/var/log/cocoonr/send_queued_mails_worker.err
stdout_logfile=/var/log/cocoonr/send_queued_mails_worker.log
Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87