Skip to content

Instantly share code, notes, and snippets.

@rassie
Created July 30, 2012 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rassie/3206764 to your computer and use it in GitHub Desktop.
Save rassie/3206764 to your computer and use it in GitHub Desktop.
Django view for applying webassets bundles per file
# prefix option in the bundle is set to '__assets__'
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
url(r'^__assets__/static/(?P<url>.*\.css)$', 'views.filter_css'),
url(r'^__assets__/static/(?P<url>.*\.less)$', 'views.filter_css'),
(r'^__assets__/static/(?P<rest>.*)$', redirect_to, {'url': '/static/%(rest)s'} ),
)
from django.http import HttpResponse
from django.http import Http404
from django.contrib.staticfiles.finders import find
from django_assets.env import get_env
from django_assets import Bundle
import StringIO
def filter_css(request, url):
filepath = find(url)
if not filepath:
raise Http404("'%s' could not be found" % filepath)
env = get_env()
our_bundle = [bundle for bundle in env if url in bundle.contents]
if not our_bundle:
try:
file = open(filepath)
try:
data = file.read().decode('utf-8')
finally:
file.close()
return HttpResponse(data, mimetype='text/css')
except IOError:
raise Http404("'%s' could not be opened" % filepath)
b = Bundle(url, filters=our_bundle[0].filters, debug=our_bundle[0].debug, output=our_bundle[0].output)
output = StringIO.StringIO()
b.build(env=env, force=True, output=output)
data = output.getvalue()
output.close()
return HttpResponse(data, mimetype='text/css')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment