首页 > 其他分享 >扩展Django:实现自己的manage命令

扩展Django:实现自己的manage命令

时间:2023-08-04 19:35:08浏览次数:40  
标签:core management name manage 扩展 module django py Django

我们都用过Django的django-admin.py和manage.py。django-admin.py是一个命令行工具,可以执行一些管理任务,比如创建Django项目。而manage.py是在创建每个Django project时自动添加在项目目录下的,只是对manage.py的一个简单包装,其功能是将Django project放到sys.path目录中,同时设置DJANGO_SETTINGS_MODULE环境变量为当前project的setting.py文件。


django-admin.py调用django.core.management来执行命令:

#!/usr/bin/env python
from django.core import management
    
if __name__ == "__main__":
   management.execute_from_command_line()

excute_from_command_line()函数会根据命令行参数解析出命令的名称,根据命令名称调用相应的Command执行命令。Command位于各个管理模块的commands模块下面。

所谓管理模块,是指在app模块下的名字为management的模块。Django通过django.core.management.find_management_module函数发现"管理模块"最后,通过django.core.management.load_command_class函数加载该.py文件中的Command类:

django.core.management.find_management_module()
def find_management_module(app_name):
    """
    Determines the path to the management module for the given app_name,
    without actually importing the application or the management module.

    Raises ImportError if the management module cannot be found for any reason.
    """
    parts = app_name.split('.')
    parts.append('management')
    parts.reverse()
    part = parts.pop()
    path = None




然后通过django.core.management.find_commands函数找到命令类。find_commands函数会在管理模块下查找.py文件,并将.py文件的名称匹配到命令名称:



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')
    try:
        return [f[:-3] for f in os.listdir(command_dir)
           if not f.startswith('_') and f.endswith('.py')]
    except OSError:
    return []

在执行命令的时候,会执行相应Command类的handle方法。所有的Command类都应该是django.core.management.base.BaseCommand的直接或间接子类。

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()


原理搞清楚了,扩展manage命令就很容易了。创建一个app并加入到settings的INSTALLED_APPS中,在该app下面创建management.commands模块,并创建hello.py文件:

from django.core.management.base 
import BaseCommand, CommandErrorfrom django.db 
import models
from placeholders import 
*import os
class Command(BaseCommand):     
    def handle(self, *args, **options):         
    print 'hello, django!'

就可以使用hello命令了:

$ python manage.py hello
hello, django!

 

标签:core,management,name,manage,扩展,module,django,py,Django
From: https://www.cnblogs.com/YaoZhouyi/p/17606815.html

相关文章

  • Django-4.2博客开发教程:初识模板(九)
    一、模板简介为了更好的维护和展示页面数据,使用直接返回数据显然是呆板的,不够美观,不够灵活,所以要使用模板。模板一般都放到项目根目录下的templates文件夹里。模板包含一些基础的HTML代码和一些特殊的语法,通过特殊的语法将数据动态的插入HTML页面中。特殊的语法中有一些变量......
  • 如何导出 Visual Studio Code 的扩展应用,并离线安装?
    如何导出VisualStudioCode的扩展应用,并离线安装?warrior210已于2022-08-0810:37:51修改2262收藏5文章标签:vscodeide编辑器版权1.离线情形VisualStudioCode的扩展应用安装位置在文件夹.vscode/extensions下。不同平台,它位于:Windows%USERPROFILE%\.vscode\exte......
  • Spring 容器里 Bean 生命周期中可扩展的 SpringBoot 接口
    Gitee:Demo源码1.ApplicationContextInitializer这是整个spring容器在刷新之前初始化ConfigurableApplicationContext的回调接口。@Slf4jpublicclassTestApplicationContextInitializerimplementsApplicationContextInitializer{@Overridepublicvoidi......
  • 爷情节!终于可以离线安装浏览器扩展了~
    现在基本只用Chrome浏览器,身边很多同事也一样。上次装了一个视频录制扩展,可能是因为扩展文件太大,同步扩展花了好长时间。有时不想把账号登得导出都是,又想使用扩展。所以能下载到.crx文件就很重要。昨天听说bejson上线了crx下载地址解析功能,于是迫不及待地去体验了一下,一个字“牛鼻......
  • Managed Debugging Assistants (zz)
    GettingRIDofJust-In-Timedebugge//z2013-08-0817:15:[email protected][T300,L4609,R130,V3618]AfterVisualStudioisinstalledonaserver,thedefaultbehaviorwhenanunhandledexceptionoccursistoshowan Exception dialogthatrequ......
  • websocke在django中使用
    目录一、websocket介绍:二、后端1.安装(基于django3.x)2.settings配置3.修改asgi文件(默认不支持websocket,只支持http)一、websocket介绍:channels4.0之后默认不带Daphne服务器了。解决方案可以有两种:1.指定channels的版本为3.x;2.安装时使用pip3install-Uchannels[“dap......
  • 【设计模式】装饰器模式Decorator:在基础组件上扩展新功能
    (目录)装饰器模式看上去和适配器模式、桥接模式很相似,都是使用组合方式来扩展原有类的,但其实本质上却相差甚远呢。简单来说,适配器模式侧重于转换,而装饰模式侧重于动态扩展;桥接模式侧重于横向宽度的扩展,而装饰模式侧重于纵向深度的扩展。原理装饰模式的原始定义是:允许动态地向......
  • WebRTC研究:RTP报头扩展
    RTPHeaderRTP协议中,RTPHeader(报头)包括固定报头(FixedHeader)与报头扩展(Headerextension,可选)。RTPFixedHeader结构如下,其中前12字节是每个RTP包必须包含的。01230123456789012345678......
  • 三步教你怎么使用iSCSI Manager,你GET了吗?
    铁威马有很多实用的功能,帮助我们更好的保存数据。铁威马的iSCSIManager可帮助您轻松管理和监控iSCSI服务。挂载成功之后,您访问iSCSILUN的虚拟磁盘就像访问本地存储空间一样方便。那么怎么使用iSCSIManager?下面分三大步为大家详细介绍该用法,快速上手不在话下~ 01如何下......
  • Django 模型(数据库)
    Django模型是与数据库相关的,与数据库相关的代码一般写在 models.py本节的代码:(Django1.6,Python2.7测试环境)learn_models.zip大家可以按照我的步骤来开始做:django-admin.pystartprojectlearn_models#新建一个项目cdlearn_models#......