pythondjangopython-daemon

Django how to run external module as Daemon


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.


Solution

  • 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