Search code examples
pythondjangodjango-manage.pydjango-management-command

Django Task/Command Execution Best Practice/Understanding


I've got a little problem with understanding the django management commands. I've got an Webapplication which displays some network traffic information through eth0. Therefore I've created a python class which analyse the traffic and create/update the specific data in the database. Something like this:

class Analyzer:
    def doSomething(self):
        #analyze the traffic create/update data in db 
    def startAnalyzing(self):
        while 1:
              self.doSomething()

Then I create a management command which creates this class instance and runs startAnalyzing().

Now my question:

Is this the correct way to do that over management command because the task is not terminating (run the whole time) and not started/stopped via webapplication? Or what is the correct way?

Is it probably better to start the "Analyzer" not via django? Im new to django and wan't to do it the right way.

Is it possible to start sniffing the traffic when i run: manage.py runserver 0.0.0.0:8080?

Many thanks in advance.


Solution

  • What you're doing is not intended to do with management commands. In fact management commands are what the name implies, a command to manage something, do a quick action. Not keep a whole process running for the entire life time of the web app.

    To achieve what you want, you should write a simple python script and keep it running with a process manager (supervisor ?). You just then have to setup django in the beginning of the script so can have access to Django's ORM, which probably is the reason you've chosen Django.

    So all in all, you're script would look something like the following:

    import sys, os
    sys.path.insert(0, "/path/to/parent/of/project") # /home/projects/django-proj
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'proj.settings')
    
    import django
    django.setup() 
    
    from proj.app.models import DBModel
    

    This way you can use django's ORM as you would use in a normal Django application. You can also provide templates and views of the Database as you normally would.

    The only thing that remains is to keep the script running, and that you can simply do with supervisord.