Django扩展自定义manage命令
使用django开发,对python manage.py ***命令模式肯定不会陌生。比较常用的有runserver,migrate。。。
本文讲述如何自定义扩展manage命令。
1、源码分析
manage.py文件是通过django-admin startproject project_name生成的。
1)manage.py的源码
a)首先设置了settings文件,本例中CIServer指的是project_name。
b)其次执行了一个函数django.core.management.execute_from_command_line(sys.argv),这个函数传入了命令行参数sys.argv
#!/usr/bin/env python
import os
import sys if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CIServer.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and available "
"on your PATH environment variable? Did you forget to activate a "
"virtual environment?"
)
execute_from_command_line(sys.argv)
2)execute_from_command_line
里面调用了ManagementUtility类中的execute方法
def execute_from_command_line(argv=None):
"""
A simple method that runs a ManagementUtility.
"""
utility = ManagementUtility(argv)
utility.execute()
在execute中主要是解析了传入的参数sys.argv,并且调用了get_command()
3)get_command
def get_commands():
"""
Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and
in each installed application -- if a commands package exists, all commands
in that package are registered. Core commands are always included. If a settings module has been
specified, user-defined commands will also be included. The dictionary is in the format {command_name: app_name}. Key-value
pairs from this dictionary can then be used in calls to
load_command_class(app_name, command_name) If a specific version of a command must be loaded (e.g., with the
startapp command), the instantiated module can be placed in the
dictionary in place of the application name. The dictionary is cached on the first call and reused on subsequent
calls.
"""
commands = {name: 'django.core' for name in find_commands(upath(__path__[0]))} if not settings.configured:
return commands for app_config in reversed(list(apps.get_app_configs())):
path = os.path.join(app_config.path, 'management')
commands.update({name: app_config.name for name in find_commands(path)}) return commands
get_command里遍历所有注册的INSTALLED_APPS路径下的management寻找(find_commands)用户自定义的命令。
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')
# Workaround for a Python 3.2 bug with pkgutil.iter_modules
sys.path_importer_cache.pop(command_dir, None)
return [name for _, name, is_pkg in pkgutil.iter_modules([npath(command_dir)])
if not is_pkg and not name.startswith('_')]
可以发现并注册的命令是commands目录下不以"_"开头的文件名。
4)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()
5)Command类
Command类要继承BaseCommand类,其中很多方法,一定要实现的是handle方法,handle方法是命令实际执行的代码。
2、如何实现自定义命令
根据上面说的原理,我们只需要在app目录中建立一个目录management,并且在下面建立一个目录叫commands,下面增加一个文件,叫hello.py即可。
要注意一下几点
1)说是目录,其实应该是包,所以在management下面和commands下面都要添加__init__.py。
2)app一定要添加在INSTALLED_APPS中,不然命令加载不到。
应该是这样的

在hello.py中实现命令的具体内容
#-*- coding:utf-8 -*-
from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument(
'-n',
'--name',
action='store',
dest='name',
default='close',
help='name of author.',
) def handle(self, *args, **options):
try:
if options['name']:
print 'hello world, %s' % options['name'] self.stdout.write(self.style.SUCCESS('命令%s执行成功, 参数为%s' % (__file__, options['name'])))
except Exception, ex:
self.stdout.write(self.style.ERROR('命令执行出错'))
执行方式
python manage.py hello -n kangaroo hello world, kangaroo
命令hello.py执行成功,参数为kangaroo
Django扩展自定义manage命令的更多相关文章
- django实现自定义manage命令的扩展
在Django开发过程中我们都用过django-admin.py和manage.py命令. django-admin.py是一个命令行工具,可以执行一些管理任务,比如创建Django项目.而manag ...
- Django分析之如何自定义manage命令
我们都用过Django的manage.py的命令,而manage.py是在我们创建Django项目的时候就自动生成在根目录下的一个命令行工具,它可以执行一些简单的命令,其功能是将Django proj ...
- 在django项目中自定义manage命令(转)
add by zhj 是我增加的注释 原文:http://www.cnblogs.com/holbrook/archive/2012/03/09/2387679.html 我们都用过Django的dj ...
- Django编写自定义manage.py 命令
官网文档地址:编写自定义 django-admin 命令 金句: 你所浪费的今天,正是昨天死的人所期待的明天. 开篇话: python manage.py <command> 的命令我们用 ...
- Django项目中自定义manage命令
挺不错的一篇文章:https://www.cnblogs.com/ajianbeyourself/p/3643304.html
- 【Django】如何自定义manage.py命令? 达到启动后台进程的目的?
代码: #-*- coding:utf- -*- """ The handle active user mail send """ from ...
- 第六章:Django 综合篇 - 5:自定义django-admin命令
我们可以通过manage.py编写和注册自定义的命令. 自定义的管理命令对于独立脚本非常有用,特别是那些使用Linux的crontab服务,或者Windows的调度任务执行的脚本.比如,你有个需求,需 ...
- 自定义django-admin命令
我们可以通过manage.py编写和注册自定义的命令. 自定义的管理命令对于独立脚本非常有用,特别是那些使用Linux的crontab服务,或者Windows的调度任务执行的脚本.比如,你有个需求,需 ...
- Django 之 流程和命令行工具
一.一个简单的web框架 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. 对于所 ...
随机推荐
- Git和Github简单教程(收藏)
原文链接:Git和Github简单教程 目录: 零.Git是什么 一.Git的主要功能:版本控制 二.概览 三.Git for Windows软件安装 四.本地Git的使用 五.Github与Git的 ...
- VMware bridge 桥接方式连接internet
经过反复测试,关于VMware内虚拟机(包括ubuntu linux和windows)连接internet 目前的结论是 使用bridge方式时,VMware相当于一个交换机(switch),虚拟机和 ...
- 基于NIOS-II的示波器:PART2 界面动态显示功能
本文所有的硬件基础以及工程参考来自魏坤示波仪,重新实现驱动并重构工程. version 0.2 界面动态显示功能 界面显示功能原理 显示波形有如下两个方案: 每一帧直接重绘显示界面,再显示下一帧图形 ...
- Java代理详解
一.概述 代理模式是Java常用的设计模式之一,实现代理模式要求代理类和委托类(被代理的类)具有相同的方法(提供相同的服务),代理类对象自身并不实现真正的核心逻辑,而是通过调用委托类对象的相关方法来处 ...
- Java log4j使用
log4j下载地址: http://logging.apache.org/log4j/1.2/download.html 本人用的是log4j-1.2.17.jar的jar包. 接下来我们配置下一lo ...
- 转: 【Java并发编程】之二十一:并发新特性—阻塞队列和阻塞栈(含代码)
转载请注明出处:http://blog.csdn.net/ns_code/article/details/17511147 阻塞队列 阻塞队列是Java5并发新特性中的内容,阻塞队列的接口是Java. ...
- 201521123015《Java程序设计》第1周学习总结
1.本周学习总结 知道了JAVA语言的发展历史和目前使用的版本,还有什么是JDK(Java Development Kit).JRE (Java Runtime Environment).JVM(Ja ...
- ZIP格式
总体格式 分文件头+文件压缩数据 中心目录+中心目录记录结束符 1.分文件头信息 0X 50 4b 03 04 分文件头信息标志,一般是zip文件的开头,可以通过这个判断文件格式 14 00 解压缩所 ...
- Hyperledger Fabric 1.0 从零开始(三)——环境构建(内网/准离线)
有公网环境的服务器可以直接看 Hyperledger Fabric 1.0 从零开始(二)--环境构建(公网) ,本篇内容与上篇相似,只不过环境搭建需要在内网下,也就是网络被限制的情况下. 1:环境构 ...
- Python爬虫2----------运用代理访问
为request添加一个代理,及将浏览器头部信息加入,随机从ip列表中拿出一个ip进行访问 注意函数参数的形式,如request.proxyhandler(协议,地址) import urllib.r ...