【Django】如何自定义manage.py命令? 达到启动后台进程的目的?

本文介绍如何在Django项目中创建自定义管理命令,包括创建步骤、关键代码及执行方式,帮助开发者更好地理解和使用Django的管理命令。

代码:

#-*- coding:utf-8 -*-
"""
The handle active user mail send
"""


from django.core.management.base import BaseCommand, CommandError
from django.db import models
#from placeholders import *
import os
import time
import logging

logger = logging.getLogger("file_protect.alarm_handler")
logger = logging.getLogger("file_protect.views")

class Command(BaseCommand):
    def handle(self, *args, **options):
        print 'hello, django!'
        while(True):
            logger.debug("hello, django")
            time.sleep(5)

 

启动

####################系统软件安装-使用apt-get安装####################
apt-get update -qq -y
apt-get install libmysqlclient-dev python-dev -qq -y
apt-get install libmysqlclient-dev python-dev daemon -qq -y


#################启动日志处理Daemon#############################
if daemon -n alarm_handler_daemon --running; then
    daemon -n alarm_handler_daemon --stop
fi

while daemon -n alarm_handler_daemon --running; do
    sleep 1
done

daemon -n alarm_handler_daemon -r /opt/ENV/ubuntu1227/bin/python $API_PROJECT_DIR/manage.py alarm_handler
echo "alarm_handler_daemon is running"

 

 

我们都用过Django的django-admin.py和manage.py。django-admin.py是一个命令行工具,可以执行一些管理任务,比如创建Django项目。而manage.py是在创建每个Django project时自动添加在项目目录下的,只是对manage.py的一个简单包装,其功能是将Django project放到sys.path目录中,同时设置DJANGO_SETTINGS_MODULE环境变量为当前project的setting.py文件。


django-admin.py调用django.core.management来执行命令:

#!/usr/bin/env python
from django.core import management

if __name__ == "__main__":
management.execute_from_command_line()

excute_from_command_line()函数会根据命令行参数解析出命令的名称,根据命令名称调用相应的Command执行命令。Command位于各个管理模块的commands模块下面。

所谓管理模块,是指在app模块下的名字为management的模块。Django通过django.core.management.find_management_module函数发现"管理模块":

复制代码
django.core.management.find_management_module()
def find_management_module(app_name):
"""
Determines the path to the management module for the given app_name,
without actually importing the application or the management module.

Raises ImportError if the management module cannot be found for any reason.
"""
parts = app_name.split('.')
parts.append('management')
parts.reverse()
part = parts.pop()
path = None
复制代码


然后通过django.core.management.find_commands函数找到命令类。find_commands函数会在管理模块下查找.py文件,并将.py文件的名称匹配到命令名称:

复制代码
def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
names that are available.

Returns an empty list if no commands are defined.
"""
command_dir = os.path.join(management_dir, 'commands')
try:
return [f[:-3] for f in os.listdir(command_dir)
if not f.startswith('_') and f.endswith('.py')]
except OSError:
return []
复制代码

最后,通过django.core.management.load_command_class函数加载该.py文件中的Command类:

复制代码
def load_command_class(app_name, name):
"""
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
复制代码

在执行命令的时候,会执行相应Command类的handle方法。所有的Command类都应该是django.core.management.base.BaseCommand的直接或间接子类。

原理搞清楚了,扩展manage命令就很容易了。创建一个app并加入到settings的INSTALLED_APPS中,在该app下面创建management.commands模块,并创建hello.py文件:

复制代码
from django.core.management.base import BaseCommand, CommandError
from django.db import models
#from placeholders import *
import os

class Command(BaseCommand):
def handle(self, *args, **options):
print 'hello, django!'
复制代码

就可以使用hello命令了:

$ python manage.py hello
hello, django!

 

参考资料:

扩展:http://www.cnblogs.com/holbrook/archive/2012/03/09/2387679.html

https://www.v2ex.com/t/58381

http://janetriley.net/2014/11/quick-how-to-custom-django-management-commands.html

http://www.cnblogs.com/linjiqin/p/3965046.html

https://www.v2ex.com/t/58381

https://github.com/mitnk/tengtweets/blob/master/manage.py

 

转载于:https://www.cnblogs.com/junneyang/p/5963030.html

Traceback (most recent call last): File "D:\hyx_medical\manage.py", line 11, in <module> from backend.models import ImageTask File "D:\hyx_medical\backend\models.py", line 2, in <module> from django.contrib.auth.models import User File "D:\Miniconda3\envs\523\lib\site-packages\django\contrib\auth\models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "D:\Miniconda3\envs\523\lib\site-packages\django\contrib\auth\base_user.py", line 57, in <module> class AbstractBaseUser(models.Model): File "D:\Miniconda3\envs\523\lib\site-packages\django\db\models\base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "D:\Miniconda3\envs\523\lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "D:\Miniconda3\envs\523\lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. PS D:\hyx_medical> python manage.py runserver Traceback (most recent call last): File "D:\hyx_medical\manage.py", line 11, in <module> from backend.models import ImageTask File "D:\hyx_medical\backend\models.py", line 2, in <module> from django.contrib.auth.models import User File "D:\Miniconda3\envs\523\lib\site-packages\django\contrib\auth\models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "D:\Miniconda3\envs\523\lib\site-packages\django\contrib\auth\base_user.py", line 57, in <module> class AbstractBaseUser(models.Model): File "D:\Miniconda3\envs\523\lib\site-packages\django\db\models\base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "D:\Miniconda3\envs\523\lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "D:\Miniconda3\envs\523\lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "D:\Miniconda3\envs\523\lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "D:\Miniconda3\envs\523\lib\site-packages\django\conf\__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
最新发布
06-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值