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命令(转)的更多相关文章

  1. Django项目中自定义manage命令

    挺不错的一篇文章:https://www.cnblogs.com/ajianbeyourself/p/3643304.html

  2. django实现自定义manage命令的扩展

    在Django开发过程中我们都用过django-admin.py和manage.py命令. django-admin.py是一个命令行工具,可以执行一些管理任务,比如创建Django项目.而manag ...

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

    代码: #-*- coding:utf- -*- """ The handle active user mail send """ from ...

  4. django项目中遇到要实现定时任务

    django项目中遇到要实现定时任务,所以选用了简单易用的django-crontab插件. 1.安装 django-crontab pip install django-crontab 2.定时要执 ...

  5. celery 分布式异步任务框架(celery简单使用、celery多任务结构、celery定时任务、celery计划任务、celery在Django项目中使用Python脚本调用Django环境)

    一.celery简介: Celery 是一个强大的 分布式任务队列 的 异步处理框架,它可以让任务的执行完全脱离主程序,甚至可以被分配到其他主机上运行.我们通常使用它来实现异步任务(async tas ...

  6. Django项目中添加富文本编辑器django-ckeditor

    django-ckeditor库的使用步骤: 1.在命令行下安装django-ckeditor这个库: 命令:pip install django-ckeditor 2.安装成功后,配置Django项 ...

  7. 擦他丫的,今天在Django项目中引用静态文件jQuery.js 就是引入报错,终于找到原因了!

    擦 ,今天在Django项目中引用静态文件jQuery.js 就是引入报错,终于找到原因了! 问题在于我使用的谷歌浏览器,默认使用了缓存,导致每次访问同一个url时,都返回的是缓存里面的东西.通过谷歌 ...

  8. django 项目中使用多数据库 multiple databases

    假如在一个django项目中使用到了不只一个数据库, 其实这在大一点的工程中很常见,比如主从库 那么会涉及到如下一些东西 1, 定义 在settings中的DATABASE中定义会使用到的数据,比如除 ...

  9. Django项目中"expected str, bytes or os.PathLike object, not list"错误解决:

    对于这个错误,也在于自己对django基础的掌握不是很牢固,忽略了MEDIA_ROOT的类型是string,而不是list. 错误的写法: MEDIA_ROOT = [ os.path.join(BA ...

随机推荐

  1. linux clamav杀毒软件的安装

    一.概述 Linux比其它操作系统更稳定更安全.理论上Linux是有可能被病毒侵害的.但实际上 Linux机器几乎不可能遭受病毒的攻击.所以我这里的问题是为什么要为Linux准备防病毒软件,为了更好理 ...

  2. iOS富文本组件的实现—DTCoreText源码解析 渲染篇

    本文转载至 http://blog.cnbang.net/tech/2729/ 上一篇介绍了DTCoreText怎样把HTML+CSS解析转换成NSAttributeString,本篇接着看看怎样把N ...

  3. LOCAL_WHOLE_STATIC_LIBRARIES与LOCAL_STATIC_LIBRARIES的区别

    在分析Jelly Bean Audio Subsystem的时候,发现HAL层的库audio_policy.xxx.so与其依赖的静态库libaudiopolicy_legacy.a都有audio_p ...

  4. 124、@JavascriptInterface

    targetSdkVersion 是设置希望的SDK版本,如果设置了此属性,那么在程序执行时,如果目标设备的API版本正好等于此数值,他会告诉Android平台:此程序在此版本已经经过充分测,没有问题 ...

  5. PHP中常见问题总结

    [1]页面之间无法传递变量 get,post,session在最新的php版本中自动全局变量是关闭的,所以要从上一页面取得提交过来得变量要使用$_GET['foo'],$_POST['foo'],$_ ...

  6. linux mutex

    #include <iostream> #include <queue> #include <cstdlib> #include <unistd.h> ...

  7. Android设计和开发系列第二篇:Action Bar(Design)

    Action Bar The action bar is a dedicated piece of real estate at the top of each screen that is gene ...

  8. 【MySQL8】 安装后的简单配置(主要解决navicat等客户端登陆报错问题)

    一.navicat等客户端登陆报错的原因 使用mysql,多数我们还是喜欢用可视化的客户端登陆管理的,个人比较喜欢用navicat.一般装好服务器以后,习惯建一个远程的登陆帐号,在mysql8服务器上 ...

  9. 中国标准时间、‘yyyy-MM-dd’格式时间转为时间戳

    中国标准时间转为时间戳 let _time="Tue Mar 20 2018 00:00:00 GMT+0800 (中国标准时间)"; console.log(Date.parse ...

  10. linux route命令详解

    考试题一:linux下如何添加路由(百度面试题) 以上是原题,老男孩老师翻译成如下3道题. a.如何用命令行方式给linux机器添加一个默认网关,假设网关地址为10.0.0.254? b. 192.1 ...