使用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命令的更多相关文章

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

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

  2. Django分析之如何自定义manage命令

    我们都用过Django的manage.py的命令,而manage.py是在我们创建Django项目的时候就自动生成在根目录下的一个命令行工具,它可以执行一些简单的命令,其功能是将Django proj ...

  3. 在django项目中自定义manage命令(转)

    add by zhj 是我增加的注释 原文:http://www.cnblogs.com/holbrook/archive/2012/03/09/2387679.html 我们都用过Django的dj ...

  4. Django编写自定义manage.py 命令

    官网文档地址:编写自定义 django-admin 命令 金句: 你所浪费的今天,正是昨天死的人所期待的明天. 开篇话: python manage.py <command> 的命令我们用 ...

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

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

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

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

  7. 第六章:Django 综合篇 - 5:自定义django-admin命令

    我们可以通过manage.py编写和注册自定义的命令. 自定义的管理命令对于独立脚本非常有用,特别是那些使用Linux的crontab服务,或者Windows的调度任务执行的脚本.比如,你有个需求,需 ...

  8. 自定义django-admin命令

    我们可以通过manage.py编写和注册自定义的命令. 自定义的管理命令对于独立脚本非常有用,特别是那些使用Linux的crontab服务,或者Windows的调度任务执行的脚本.比如,你有个需求,需 ...

  9. Django 之 流程和命令行工具

    一.一个简单的web框架 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. 对于所 ...

随机推荐

  1. Cobbler批量部署CentOS

    简介 Cobbler是一个快速网络安装linux的服务,而且在经过调整也可以支持网络安装windows.该工具使用python开发,小巧轻便(才15k行python代码),使用简单的命令即可完成PXE ...

  2. 201521123008《Java程序设计》第七周实验总结

    1.本周学习总结 以你喜欢的方式(思维导图或其他)归纳总结集合相关内容. 2. 书面作业 1.ArrayList代码分析 1.1 解释ArrayList的contains源代码 public bool ...

  3. 201521123016 《Java程序设计》第5周学习总结

    1. 本周学习总结 1.1 尝试使用思维导图总结有关多态与接口的知识点. 2. 书面作业 1.代码阅读:Child压缩包内源代码 1.1 com.parent包中Child.java文件能否编译通过? ...

  4. Git与码云(Git@OSC)入门-如何在实验室和宿舍同步你的代码(1)

    0.几个基本概念 本地仓库:本机上某个存放代码的仓库. 远程仓库:码云服务器上的代码仓库. 重要提醒:当我们在本地操作(新增.删除.修改)文件.目录时,并将其提交(commit),就是提交到了本地仓库 ...

  5. 201521123007《Java程序设计》第11周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结多线程相关内容. 2. 书面作业 本次PTA作业题集多线程 1. 互斥访问与同步访问 完成题集4-4(互斥访问)与4-5(同步访问) ...

  6. Hibernate第七篇【对象状态、一级缓存】

    前言 本博文主要讲解Hibernate的细节-->对象的状态和一级缓存- 对象状态 Hibernate中对象的状态: - 临时/瞬时状态 - 持久化状态 - 游离状态 学习Hibernate的对 ...

  7. Java实现MD5加密_字符串加密_文件加密

    Java实现MD5加密,具体代码如下: package com.bstek.tools; import java.io.FileInputStream; import java.io.IOExcept ...

  8. C++初学 virtual 相关

    声明: 1.为了节省篇幅,头文件和域什么的都没写.另外可能是java转C++,有些叫法可能会不对 2.因初学,都是自己摸索的,有错望指出,勿喷 假设父类声明 Parent.h中如下 class Par ...

  9. java实现excel和数据的交互

    1. 环境要求 本文环境为: 数据库为oracle,jdk为jdk7,依赖jar包为ojdbc6-11.2.0.4.0.jar+poi-3.14.jar 2.POI 使用 1. 建立工作空间 2. 获 ...

  10. 一款简洁而强大的前端框架JQUery—动画效果及剪刀石头布小游戏

    jQuery是什么? jQuery是一个快速.简洁的JavaScript框架,它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作.事件处理.动画 ...