Skip to content

Instantly share code, notes, and snippets.

@emesik
Created October 13, 2010 11:54
Show Gist options
  • Save emesik/623881 to your computer and use it in GitHub Desktop.
Save emesik/623881 to your computer and use it in GitHub Desktop.
from django.conf import settings
from django.http import HttpResponse, HttpResponseNotFound
import os
import re
import clevercss
def serve_css(request, path):
css_fname = os.path.join(settings.MEDIA_ROOT, path)
ccss_fname = os.path.join(settings.MEDIA_ROOT, re.compile('\.css$').sub('.ccss', path))
css = ccss = None
if os.path.exists(css_fname):
css_file = open(css_fname, 'rb')
css = css_file.read()
css_file.close()
if os.path.exists(ccss_fname):
ccss_file = open(ccss_fname, 'rb')
ccss = ccss_file.read().decode('utf-8')
ccss_file.close()
response = HttpResponse(mimetype='text/css')
if not ccss:
if css:
response.write(css)
return response
return HttpResponseNotFound()
if css and os.stat(css_fname)[8] > os.stat(ccss_fname)[8]:
response.write(css)
return response
css_file = open(css_fname, 'wb')
css = clevercss.convert(ccss)
css_file.write(css.encode('utf-8'))
css_file.close()
response.write(css)
return response
if settings.DEBUG:
urlpatterns += patterns('',
(r'media/(?P<path>.*\.css)$', 'clevercss_helper.serve_css'),
(r'media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment