在django项目中自定义manage命令(转)
add by zhj 是我增加的注释
原文:http://www.cnblogs.com/holbrook/archive/2012/03/09/2387679.html
我们都用过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 文件。(add by zhj 如果只有一个django project,那用manage.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文件,目录结构为(add by zhj)
- app_name
├── __init__.py- ├── management
- │ ├── commands
- │ │ ├── __init__.py
- │ │ └── hello.py
- │ └── __init__.py
- ├── models.py
- ├── tests.py
- └── views.py
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!
在django项目中自定义manage命令(转)的更多相关文章
- Django项目中自定义manage命令
挺不错的一篇文章:https://www.cnblogs.com/ajianbeyourself/p/3643304.html
- django实现自定义manage命令的扩展
在Django开发过程中我们都用过django-admin.py和manage.py命令. django-admin.py是一个命令行工具,可以执行一些管理任务,比如创建Django项目.而manag ...
- 【Django】如何自定义manage.py命令? 达到启动后台进程的目的?
代码: #-*- coding:utf- -*- """ The handle active user mail send """ from ...
- django项目中遇到要实现定时任务
django项目中遇到要实现定时任务,所以选用了简单易用的django-crontab插件. 1.安装 django-crontab pip install django-crontab 2.定时要执 ...
- celery 分布式异步任务框架(celery简单使用、celery多任务结构、celery定时任务、celery计划任务、celery在Django项目中使用Python脚本调用Django环境)
一.celery简介: Celery 是一个强大的 分布式任务队列 的 异步处理框架,它可以让任务的执行完全脱离主程序,甚至可以被分配到其他主机上运行.我们通常使用它来实现异步任务(async tas ...
- Django项目中添加富文本编辑器django-ckeditor
django-ckeditor库的使用步骤: 1.在命令行下安装django-ckeditor这个库: 命令:pip install django-ckeditor 2.安装成功后,配置Django项 ...
- 擦他丫的,今天在Django项目中引用静态文件jQuery.js 就是引入报错,终于找到原因了!
擦 ,今天在Django项目中引用静态文件jQuery.js 就是引入报错,终于找到原因了! 问题在于我使用的谷歌浏览器,默认使用了缓存,导致每次访问同一个url时,都返回的是缓存里面的东西.通过谷歌 ...
- django 项目中使用多数据库 multiple databases
假如在一个django项目中使用到了不只一个数据库, 其实这在大一点的工程中很常见,比如主从库 那么会涉及到如下一些东西 1, 定义 在settings中的DATABASE中定义会使用到的数据,比如除 ...
- Django项目中"expected str, bytes or os.PathLike object, not list"错误解决:
对于这个错误,也在于自己对django基础的掌握不是很牢固,忽略了MEDIA_ROOT的类型是string,而不是list. 错误的写法: MEDIA_ROOT = [ os.path.join(BA ...
随机推荐
- 使用pyinotify监控文件系统的变化
pyinotify依赖Linux内核inotify功能,它需要在2.6.13版本的内核的Linux系统上运行. 1. 安装pyinotify pip install pyinotify 安装完后可以直 ...
- RAC的搭建(三)--Grid的安装
1. 安装cvuqdisk.rpm补丁包 在两个Oracle RAC 所有节点上安装操作系统程序包cvuqdisk.如果没有cvuqdisk,集群验证实用程序就无法发现共享磁盘. 该包在p104045 ...
- Barcode.js功能强大的条码生成jQuery插件
本文转载自http://www.uedsc.com/barcode-js.html Barcode.js是一个基于jQuery库的插件,用于绘制条形码或者二维码,能够生成基于DIV+CSS或者Canv ...
- 【node.js】】MSBUILD : error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。
错误原因:缺少windows构建插件 解决方法: # (全局安装windows构建工具) npm install --global --production windows-build-tools
- 布式实时日志系统(三) 环境搭建之centos 6.4下hadoop 2.5.2完全分布式集群搭建最全资料
最近公司业务数据量越来越大,以前的基于消息队列的日志系统越来越难以满足目前的业务量,表现为消息积压,日志延迟,日志存储日期过短,所以,我们开始着手要重新设计这块,业界已经有了比较成熟的流程,即基于流式 ...
- mvc4 初体验(一)
[AllowAnonymous] [AllowAnonymous] 属性,允许匿名 在BaseControler里面加一个[Authorize],所有要验证的页面都继承BaseControler, 不 ...
- Elasticsearch学习之深入搜索四 --- cross-fields搜索
1. cross-fields搜索 一个唯一标识,跨了多个field.比如一个人,标识,是姓名:一个建筑,它的标识是地址.姓名可以散落在多个field中,比如first_name和last_name中 ...
- Telnet是什么意思又是什么协议 Telnet有什么作用及功能
Telnet是teletype network的缩写,专业的说,Telnet是Internet上远程登录的一种程序:它可以让您的电脑通过网络登录到网络另一端的电脑上,甚至还可以存取那台电脑上的文件. ...
- 使用 intellijIDEA + gradle构建的项目如何debug
在intellij IDEA里建立gradle项目(使用jett插件的web项目) 使用intellijIDEA提供的debug无效(无法进入断点) 摸索了一下,通过远程调试的方法来进行调试是可行的 ...
- VS NuGet加载本地程序包
NuGet是VS中非常实用的一个工具,我们可以通过它在线安装想要的程序包,只要右键点击解决方案中的项目的引用,在弹出的菜单中选择“管理NuGet程序包”,然后就可以通过在线搜索找到想要添加的程序包,下 ...