2019-11-22 10:57:10 +00:00
|
|
|
import os
|
|
|
|
from sass import compile
|
2020-03-22 18:57:48 +00:00
|
|
|
from django.conf import settings
|
|
|
|
|
|
|
|
def locate(filename):
|
2020-03-22 20:19:12 +00:00
|
|
|
for path, dirs, files in os.walk(os.getcwd(), followlinks=True):
|
2020-03-22 18:57:48 +00:00
|
|
|
for f in files:
|
|
|
|
if f == filename:
|
|
|
|
return os.path.join(path, filename)
|
2019-11-22 10:57:10 +00:00
|
|
|
|
2020-01-05 12:37:51 +00:00
|
|
|
class SassMiddleware:
|
2020-03-22 18:57:48 +00:00
|
|
|
'''Simple SASS middleware that intercepts requests for .css files and
|
|
|
|
tries to compile the corresponding SCSS file.
|
|
|
|
|
|
|
|
'''
|
2019-11-22 10:57:10 +00:00
|
|
|
def __init__(self, get_response):
|
|
|
|
self.get_response = get_response
|
|
|
|
|
|
|
|
def __call__(self, request):
|
|
|
|
if settings.DEBUG and request.path.endswith('.css'):
|
2020-03-22 18:57:48 +00:00
|
|
|
css_file = request.path.rsplit('/',1)[1]
|
|
|
|
css_path = locate(css_file)
|
|
|
|
if css_path:
|
|
|
|
sass_path = css_path[:-4]
|
|
|
|
map_path = css_path + '.map'
|
|
|
|
if os.path.exists(sass_path):
|
|
|
|
css = compile(filename=sass_path, output_style='nested')
|
|
|
|
css, mapping = compile(filename=sass_path, source_map_filename=map_path)
|
|
|
|
with open(css_path, 'w') as f:
|
|
|
|
f.write(css)
|
|
|
|
with open(map_path, 'w') as f:
|
|
|
|
f.write(mapping)
|
2019-11-22 10:57:10 +00:00
|
|
|
|
|
|
|
response = self.get_response(request)
|
|
|
|
return response
|