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,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. 对于所 ...
随机推荐
- 建立maven工程pom.xml报错:web.xml is missing and <failOnMissingWebXml> is set to true
解决方式:如图添加web.xml文件即可
- 我的天哪,现在的移动VIN码识别已经这么。。
VIN码是英文(Vehicle Identification Number)的缩写,译为车辆识别代码,又称车辆识别码,车辆识别代码,车辆识别号,车辆识别代号,VIN码是表明车辆身份的代码.VIN码由1 ...
- Java Object中的equals和hashCode
Java的Object对象中有两个方法比较有意思,一个是equals(),一个是hashCode(),那么这两个的作用有些同学可能还不是很清楚,那么同学们现在就进一步了解一下吧. 下面咱们写一个简单的 ...
- 浏览器console的用法
Leo_wlCnBlogs 自由.创新.研究.探索 Linux/Windows Mono/DotNet [ Open Source .NET Development/ 使用开源工具进行DotNet软件 ...
- 【1414软工助教】团队作业4——第一次项目冲刺(Alpha版本) 得分榜
题目 团队作业4--第一次项目冲刺(Alpha版本) 作业提交情况情况 所有团队都在规定时间内完成了七次冲刺. 往期成绩 个人作业1:四则运算控制台 结对项目1:GUI 个人作业2:案例分析 结对项目 ...
- 201521123091 《Java程序设计》第13周学习总结
Java 第十三周总结 第十三周的作业. 目录 1.本章学习总结 2.Java Q&A 3.码云上代码提交记录及PTA实验总结 4.课后阅读 1.本章学习总结 1.1 以你喜欢的方式(思维导图 ...
- 201521123113《Java程序设计》第14周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图.Onenote或其他)归纳总结多数据库相关内容. JDBC体系架构: 2. 书面作业 Q1. MySQL数据库基本操作 1.1 建立数据库test ...
- MD格式示例
一个例子: 例子开始 1. 本章学习总结 今天主要学习了三个知识点 封装 继承 多态 2. 书面作业 Q1. java HelloWorld命令中,HelloWorld这个参数是什么含义? 今天学了一 ...
- kettle工具实现报表导出的初步搭建
1.下载kettle 国外网站:http://kettle.pentaho.org/需要FQ,下载慢 2.下载完成启动(windows)-->spoon.bat 3.进入界面,两个主要的tab页 ...
- Apache Spark 2.2.0 中文文档 - Submitting Applications | ApacheCN
Submitting Applications 在 script in Spark的 bin 目录中的spark-submit 脚本用与在集群上启动应用程序.它可以通过一个统一的接口使用所有 Spar ...