简体   繁体   English

Django任务/命令执行最佳实践/理解

[英]Django Task/Command Execution Best Practice/Understanding

I've got a little problem with understanding the django management commands. 我在理解django管理命令时遇到了一些问题。 I've got an Webapplication which displays some network traffic information through eth0. 我有一个Web应用程序,它通过eth0显示一些网络流量信息。 Therefore I've created a python class which analyse the traffic and create/update the specific data in the database. 因此,我创建了一个python类,用于分析流量并创建/更新数据库中的特定数据。 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() . 然后,我创建一个管理命令,该命令创建该类实例并运行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? 这是通过管理命令执行此操作的正确方法,因为该任务没有终止(始终运行)并且没有通过Web应用程序启动/停止吗? Or what is the correct way? 还是正确的方法是什么?

Is it probably better to start the "Analyzer" not via django? 不通过Django启动“分析器”可能更好吗? Im new to django and wan't to do it the right way. 我是django的新手,所以不想做对了。

Is it possible to start sniffing the traffic when i run: manage.py runserver 0.0.0.0:8080? 当我运行时,是否可以开始监听流量:manage.py runserver 0.0.0.0:8080?

Many thanks in advance. 提前谢谢了。

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. 在Web应用程序的整个生命周期中都无法保持整个流程的运行。

To achieve what you want, you should write a simple python script and keep it running with a process manager (supervisor ?). 为了实现您想要的功能,您应该编写一个简单的python脚本,并使其在进程管理器(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. 您只需要在脚本的开头设置 django,就可以访问Django的ORM,这可能就是您选择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. 这样,您可以像在普通Django应用程序中一样使用django的ORM。 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 . 剩下的唯一事情就是保持脚本运行,而您只需要使用supervisor即可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM