使用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. Javascript学习日志(三):闭包

    说实话,前面一节的原型和原型链在当初学的时候并没有很头疼,对着高级编程第三版撸了几遍就理解透了,闭包这一节真的挺头疼的,很惭愧,看了差不多十来遍吧,还翻看了网上的其他博客和解释文档,五花八门的表达方式 ...

  2. 猎八哥浅谈MYSQL触发器

    什么是MYSQL触发器,我们先了解一下触发的意思.触发的字面意思是指因触动而激发起某种反应. MYSQL必知必会中对触发器的解释是:MySQL响应以下任意语句而自动执行的一条MySQL语句(或位于 B ...

  3. shell脚本进阶之循环判断

    p.MsoNormal,li.MsoNormal,div.MsoNormal { margin: 0cm; margin-bottom: .0001pt; text-align: justify; f ...

  4. PHP初入,简易网页整理(布局&特效的使用)

    html><html> <head> <meta charset="UTF-8"> <title></title> ...

  5. 结构体(struct)大小

    结构体(struct)大小 本文参考链接:C语言结构体(struct)常见使用方法,链接中的实例代码经实践有几处不准确,本文在引用时已做更改 注意:在结构体定义时不能申请空间(除非是结构体变量),不可 ...

  6. Js函数初学者练习(一)switch-case结构实现计算器。

      前  言 JRedu 给大家介绍一点JS函数的练习题希望初学者多做一些练习能够更好的掌握JS的函数,以及能够提升大家的逻辑思维.(我也是个渣渣希望路过的大神多提建议或意见) 希望能够对大家有所帮助 ...

  7. 团队作业7---Alpha冲刺值事后诸葛

    一.设想和目标 1.我们的软件要解决什么问题? 解决教师和助教对实验报告查重的问题,拥有两个用户:1.教师或助教:查看学生实验报告的重复率:4.学生:上传实验报告. 2.是否定义得很清楚?是否对典型用 ...

  8. 团队作业8——第二次项目冲刺(Beta阶段)--第三天

    一.Daily Scrum Meeting照片 二.燃尽图 三.项目进展 学号 成员 贡献比 201421123001 廖婷婷 16% 201421123002 翁珊 16% 201421123004 ...

  9. 201521123038 《Java程序设计》 第八周学习总结

    201521123038 <Java程序设计> 第八周学习总结 1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结集合与泛型相关内容. 从集合里面获取对象时必须进行强制类 ...

  10. 201521123056 《Java程序设计》第7周学习总结

    1. 本周学习总结 2. 书面作业 1. ArrayList代码分析 1.1 解释ArrayList的contains源代码 1.2 解释E remove(int index)源代码 1.3 结合1. ...