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,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. 对于所 ...
随机推荐
- 字符串和转为Data类型前后几天
以防忘记:SimpleDateFormat 可以设置字符串的格式 package com.apploft.util.lang;import java.text.SimpleDateFormat;imp ...
- sqlserver与mysql中vachar(n)中遇到的坑
前两天在做将mysql的数据表导入到sqlserver当中. 本人比较愚笨,操作方法 是先将mysql的数据表到处为insert脚本,再在sqlserver中执行sql脚本 在网上看了一下那些方法 , ...
- 201521123096《Java程序设计》第十二周学习总结
1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容. 2. 书面作业 将Student对象(属性:int id, String name,int age,doubl ...
- wampserver启动不起来的原因?
如果没怎么动wamp的配置文件就发现wampserver启动不起来了,那么可能你碰到了iis服务器. 原因是apache的端口占用的是80,而iis的端口占用也是80所以造成了不能启动wampserv ...
- webservice第一篇【介绍、Scoket、http调用、wsimport调用】
WebService介绍 首先我们来谈一下为什么需要学习webService这样的一个技术吧-. 问题一 如果我们的网站需要提供一个天气预报这样一个需求的话,那我们该怎么做????? 天气预报这么一个 ...
- Could not execute JDBC batch update; SQL [delete from role where roleId=?]; constraint [null]; neste
今天在写多个删除功能的时候出现了这么一个错误:意思是删除操作的时候,没有找到对应的外键. Cannot delete or update a parent row: a foreign key con ...
- 轻松把你的项目升级到PWA
什么是PWA PWA(Progressive Web Apps,渐进式网页应用)是Google在2015年推出的项目,致力于通过web app获得类似native app体验的网站. 优点 1.无需客 ...
- JVM菜鸟进阶高手之路九(解惑)
转载请注明原创出处,谢谢! 在第八系列最后有些疑惑的地方,后来还是在我坚持不懈不断打扰笨神,阿飞,ak大神等,终于解决了该问题.第八系列地址:http://www.jianshu.com/p/7f7c ...
- 阿里云linux centos 一键部署web环境--图文详解
一.购买阿里云服务器ECS 1,登录阿里云,选择阿里云服务器ECS 2,创建实例 或 3,选好配置 4,完成配置 注:记住用户名和密码 二.一键配置linux环境 1,下载xshell,安装成功后,建 ...
- css样式引入优先级?
css中的优先级讲的有 1.选择器的优先级. 2.样式引入的优先级. 今天要研究的是样式引入的优先级.网上又很多答案都是如下的,但是真的是这样的吗,让我们来探一探究竟是如何. 四种样式的优先级别是:行 ...