日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Django扩展自定义manage命令

發(fā)布時間:2024/1/17 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django扩展自定义manage命令 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用django開發(fā),對python manage.py ***命令模式肯定不會陌生。比較常用的有runserver,migrate。。。

本文講述如何自定義擴展manage命令。

?

1、源碼分析

manage.py文件是通過django-admin startproject project_name生成的。

1)manage.py的源碼

a)首先設(shè)置了settings文件,本例中CIServer指的是project_name。

b)其次執(zhí)行了一個函數(shù)django.core.management.execute_from_command_line(sys.argv),這個函數(shù)傳入了命令行參數(shù)sys.argv

#!/usr/bin/env python import os import sysif __name__ == "__main__":os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CIServer.settings")try:from django.core.management import execute_from_command_lineexcept 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

里面調(diào)用了ManagementUtility類中的execute方法

def execute_from_command_line(argv=None):"""A simple method that runs a ManagementUtility."""utility = ManagementUtility(argv)utility.execute()

在execute中主要是解析了傳入的參數(shù)sys.argv,并且調(diào)用了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, andin each installed application -- if a commands package exists, all commandsin that package are registered.Core commands are always included. If a settings module has beenspecified, user-defined commands will also be included.The dictionary is in the format {command_name: app_name}. Key-valuepairs from this dictionary can then be used in calls toload_command_class(app_name, command_name)If a specific version of a command must be loaded (e.g., with thestartapp command), the instantiated module can be placed in thedictionary in place of the application name.The dictionary is cached on the first call and reused on subsequentcalls."""commands = {name: 'django.core' for name in find_commands(upath(__path__[0]))}if not settings.configured:return commandsfor 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 commandnames 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('_')]

可以發(fā)現(xiàn)并注冊的命令是commands目錄下不以"_"開頭的文件名。

?

4)load_command_class

將命令文件***.py中的Command類加載進去。

def load_command_class(app_name, name):"""Given a command name and an application name, returns the Commandclass 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類,其中很多方法,一定要實現(xiàn)的是handle方法,handle方法是命令實際執(zhí)行的代碼。

?

2、如何實現(xiàn)自定義命令

根據(jù)上面說的原理,我們只需要在app目錄中建立一個目錄management,并且在下面建立一個目錄叫commands,下面增加一個文件,叫hello.py即可。

要注意一下幾點

1)說是目錄,其實應(yīng)該是包,所以在management下面和commands下面都要添加__init__.py。

2)app一定要添加在INSTALLED_APPS中,不然命令加載不到。

應(yīng)該是這樣的

?

在hello.py中實現(xiàn)命令的具體內(nèi)容

#-*- coding:utf-8 -*- from django.core.management.base import BaseCommand, CommandErrorclass 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執(zhí)行成功, 參數(shù)為%s' % (__file__, options['name'])))except Exception, ex:self.stdout.write(self.style.ERROR('命令執(zhí)行出錯'))

?執(zhí)行方式

python manage.py hello -n kangaroo

hello world, kangaroo
命令hello.py執(zhí)行成功,參數(shù)為kangaroo

?

轉(zhuǎn)載于:https://www.cnblogs.com/kangoroo/p/7623945.html

總結(jié)

以上是生活随笔為你收集整理的Django扩展自定义manage命令的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。