JsCompiler Filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/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

More like this

  1. Google Closure support in django-compress by fabrice.bonny 2 years, 3 months ago
  2. SOAP views with on-demand WSDL generation by chewie 3 years, 5 months ago
  3. Dynamic thumbnail generator by semente 3 years, 11 months ago
  4. YUI Loader as Django middleware by akaihola 3 years, 9 months ago
  5. Hide Emails by epicserve 2 years, 11 months ago

Comments

peterbe (on August 12, 2010):

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.

#

(Forgotten your password?)