django-simplecms/cms/middleware.py

56 wiersze
1.8 KiB
Python

import os
2021-07-03 23:59:48 +00:00
2020-03-22 18:57:48 +00:00
from django.conf import settings
from django.middleware import cache
2021-07-03 23:59:48 +00:00
from sass import compile
2020-03-22 18:57:48 +00:00
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:
yield os.path.join(path, filename)
2021-07-03 23:59:48 +00:00
class FetchFromCacheMiddleware(cache.FetchFromCacheMiddleware):
2021-07-03 23:59:48 +00:00
"""Minor change to the original middleware that prevents caching of
requests that have a `sessionid` cookie. This should be the
Django default, IMHO.
2021-07-03 23:59:48 +00:00
"""
def process_request(self, request):
2021-07-03 23:59:48 +00:00
if "sessionid" not in request.COOKIES:
return super().process_request(request)
2021-07-03 23:59:48 +00:00
class SassMiddleware:
2021-07-03 23:59:48 +00:00
"""Simple SASS middleware that intercepts requests for .css files and
2020-03-22 18:57:48 +00:00
tries to compile the corresponding SCSS file.
2021-07-03 23:59:48 +00:00
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
2021-07-03 23:59:48 +00:00
if settings.DEBUG and request.path.endswith(".css"):
css_file = request.path.rsplit("/", 1)[1]
sass_file = css_file[:-4]
sass_paths = locate(sass_file)
2020-09-13 21:16:38 +00:00
for sass_path in list(sass_paths):
if os.path.exists(sass_path):
2021-07-03 23:59:48 +00:00
css_path = sass_path + ".css"
map_path = css_path + ".map"
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:
2020-09-13 21:16:38 +00:00
f.write(css)
2021-07-03 23:59:48 +00:00
with open(map_path, "w") as f:
2020-09-13 21:16:38 +00:00
f.write(mapping)
response = self.get_response(request)
return response