2009-11-12 75 views
0

我可以調用YUI壓縮機:Java的罐子的YUICompressor-x.y.z.jar [選項]從Django的管理命令,如果讓我怎麼去這樣做[輸入文件]?Django的管理命令+銳壓縮機

我在當地發展的窗口和主機在Linux上,因此這似乎是一個解決方案,將在兩個工作。

回答

1

是的,但你必須自己寫命令的一部分。去這個問題的最好辦法是怎麼看股票命令執行或看一個項目像django-command-extensions

然而,一個更好的解決方案(即較少的工作)是使用一個項目像django-compress已經定義一個管理命令synccompress,它將調用yui壓縮器。

4

爲了擴大對範大風的答案,這是肯定可以的。下面是成分:

  • 一個應用程序,是在已安裝應用
  • 正確的目錄結構
  • Python文件以作爲它繼承關一個Django管理命令類
的命令

這裏一般是如何工作的...

當manage.py運行時,如果它找不到命令說「manage.py yui_compress」它搜索通過安裝的應用程序。它會在每個應用程序中查看是否存在app.management.commands,然後檢查該模塊中是否存在文件「yui_compress.py」。如果是這樣,它將啓動該python文件中的類並使用它。

因此,它結束了看起來像這樣...

app 
    \management 
     \commands 
      yui_compress.py 

凡yui_compress.py包含...

當然
from django.core.management.base import NoArgsCommand 

class Command(NoArgsCommand): 
    help = "Does my special action." 
    requires_model_validation = False 

    def handle_noargs(self, **options): 
     # Execute whatever code you want here 
     pass 

中 '應用' 需要在已安裝應用內settings.py。

但隨後,範確實讓一個很好的建議,以找到一個工具,它已經做了你想要的東西。 :)

+0

+1不錯的答案,我想勾畫出如何做一個命令,但沒有足夠的時間。 – 2009-11-12 23:16:34

+0

感謝您的回答。我知道如何設置管理命令,但想知道:NoArgsCommand以及如何放置在:def handle_noargs方法中? – Joe 2009-11-13 00:39:17

+0

這裏有什麼代碼是你想運行命令時運行的任何代碼。這裏有一個來自南方的例子 - http://bitbucket.org/andrewgodwin/south/src/tip/south/management/commands/convert_to_south。py因此,例如,您可以遞歸搜索MEDIA_ROOT文件夾,查找以CSS結尾的所有文件,通過YUI壓縮器運行它們,然後將它們保存爲[[originalname]] _ compressed.css。 – 2009-11-13 02:09:43

0

我最近增加了一個YUI壓縮機處理器Django的mediasync。

如果您想使用Django的mediasync本身,這裏的項目頁面: https://github.com/sunlightlabs/django-mediasync

如果你想看到的YUI壓縮機命令作爲參考,這裏是從它複製/粘貼(以防路徑在未來發生變化)...

from django.conf import settings 
import os 
from subprocess import Popen, PIPE 

def _yui_path(settings): 
    if not hasattr(settings, 'MEDIASYNC'): 
     return None 
    path = settings.MEDIASYNC.get('YUI_COMPRESSOR_PATH', None) 
    if path: 
     path = os.path.realpath(os.path.expanduser(path)) 
    return path 

def css_minifier(filedata, content_type, remote_path, is_active): 
    is_css = (content_type == 'text/css' or remote_path.lower().endswith('.css')) 
    yui_path = _yui_path(settings) 
    if is_css and yui_path and is_active: 
     proc = Popen(['java', '-jar', yui_path, '--type', 'css'], stdout=PIPE, 
        stderr=PIPE, stdin=PIPE) 
     stdout, stderr = proc.communicate(input=filedata) 
     return str(stdout) 

def js_minifier(filedata, content_type, remote_path, is_active): 
    is_js = (content_type == 'text/javascript' or remote_path.lower().endswith('.js')) 
    yui_path = _yui_path(settings) 
    if is_js and yui_path and is_active: 
     proc = Popen(['java', '-jar', yui_path, '--type', 'js'], stdout=PIPE, 
        stderr=PIPE, stdin=PIPE) 
     stdout, stderr = proc.communicate(input=filedata) 
     return str(stdout)