python - 有没有办法向现有的 django 命令添加功能?

标签 python django

我想在 django 命令启动之前运行一个命令。

例如:

$ python manage.py runserver
Validating models...

0 errors found
Django version 1.3, using settings 'creat1va.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
(started some command in the background)
[10/Jul/2011 21:50:26] "GET / HTTP/1.1" 200 1611
[10/Jul/2011 21:50:26] "GET /assets/css/master.css HTTP/1.1" 404 1783
[10/Jul/2011 21:50:26] "GET /assets/images/misc/logo.png HTTP/1.1" 404 1801
[10/Jul/2011 21:50:26] "GET /assets/images/icons/bo.gif HTTP/1.1" 404 1798
[10/Jul/2011 21:50:28] (My background process) "Some nice Feedback"

主要思想是启动后台进程,并输出日志记录。

有没有办法在不破解 Django 源代码的情况下实现这一目标?

最佳答案

只需意识到您可以轻松覆盖命令,就像使用同名命令制作应用一样。

所以我创建了一个应用程序并创建了一个与 runserver 同名的文件,然后扩展了 runserver 基类以在它运行之前添加一个新功能。

例如,我想在 runserver 启动之前运行命令 $ compass 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 命令的更多详细信息

希望有人觉得这有帮助

关于python - 有没有办法向现有的 django 命令添加功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6645051/

相关文章:

python - 二维数组意外赋值错误

python - 使用 Django 的评论框架计算 `models.py` 中每个对象的评论

django用户配置文件数据库问题

python - 如何编写查询集来显示链接到某个类别的所有产品?

python - 用于部分传输的 Vulkan VkBufferImageCopy

python - 列表理解,其中条件取决于正在生成的列表

python - 简单的 HTML 到 PDF python 库错误

python - manage.py 是如何工作的?

python - 如何在创建许多对象的 Django admin 中创建自定义按钮?

python - celery 主管 : How to restart a supervisor job to make newly updated celery-tasks working?