我想在 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/