您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

有没有一种方法可以向现有的django命令添加功能?

有没有一种方法可以向现有的django命令添加功能?

只需意识到您可以轻松地覆盖命令,就像使用具有相同名称的命令制作应用程序一样。

因此,我创建了一个应用程序,并创建了一个与runserver相同名称文件,然后扩展了runserver基类以在运行之前添加功能

例如,我想在runserver启动之前运行$ $ watch watch命令,并使其在runserver执行期间一直运行。

"""
Start $compass watch, command when you do $python manage.py runserver

file: main/management/commands/runserver.py

Add ´main´ app to the last of the installed apps
"""

from optparse import make_option
import os
import subprocess

from django.core.management.base import BaseCommand, CommandError
from django.core.management.commands.runserver import BaseRunserverCommand
from django.conf import settings

class Command(BaseRunserverCommand):
    option_list = BaseRunserverCommand.option_list + (
        make_option('--adminmedia', dest='admin_media_path', default='',
            help='Specifies the directory from which to serve admin media.'),
        make_option('--watch', dest='compass_project_path', default=settings.MEDIA_ROOT,
            help='Specifies the project directory for compass.'),
    )

    def inner_run(self, *args, **options):
        self.compass_project_path = options.get('compass_project_path', settings.MEDIA_ROOT)

        self.stdout.write("Starting the compass watch command for %r\n" % self.compass_project_path)
        self.compass_pid = subprocess.Popen(["compass watch %s" % self.compass_project_path],
            shell=True,
            stdin=subprocess.PIPE,
            stdout=self.stdout,
            stderr=self.stderr)
        self.stdout.write("Compas watch process on %r\n" % self.compass_pid.pid)

        super(Command, self).inner_run(*args, **options)

这样很好。

查看https://docs.djangoproject.com/en/dev/howto/custom-management- commands/了解有关django命令的更多详细信息

希望有人觉得这有帮助

Go 2022/1/1 18:41:14 有455人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶