#!/usr/bin/python2.4
"""JsCompiler Django template filter."""
__author__ = 'jeremydw@gmail.com (Jeremy Weinstein)'
import base64
import urllib
from django.core.cache import cache
from django import template
from django.utils import simplejson
COMPILER_SERVICE = 'http://closure-compiler.appspot.com/compile'
register = template.Library()
@register.filter
def jscomp(js):
"""Returns compiled Javascript from raw source.
Makes a remote call to Closure Compiler service to compile filter contents.
Args:
js: The raw Javascript source.
Returns:
Compiled Javascript.
"""
js_id = base64.urlsafe_b64encode(js).strip()
compiled_code = cache.get(js_id)
if not compiled_code:
params = urllib.urlencode({
'output_format': 'json',
'output_info': 'compiled_code',
'compilation_level': 'ADVANCED_OPTIMIZATIONS',
'warning_level': 'verbose',
'use_closure_library': 'true',
'js_code': js,
})
try:
response = urllib.urlopen(COMPILER_SERVICE, params).read()
except IOError:
raise Exception(
'Failed to download from: %s?%s', (COMPILER_SERVICE, params))
compiled_code = simplejson.loads(response)['compiledCode']
cache.set(js_id, compiled_code)
return compiled_code
Comments
A much more robust solution is to use django-static It doesn't use the network but instead a local compiled java class. Also this won't compile it every time you request it.
#