Created
July 30, 2012 13:09
-
-
Save rassie/3206764 to your computer and use it in GitHub Desktop.
Django view for applying webassets bundles per file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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'} ), | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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