contentdb/app/sass.py

67 lines
1.7 KiB
Python
Raw Normal View History

2018-05-09 19:35:36 +02:00
# -*- coding: utf-8 -*-
"""
A small Flask extension that makes it easy to use Sass (SCSS) with your
Flask application.
Code unabashedly adapted from https://github.com/weapp/flask-coffee2js
:copyright: (c) 2012 by Ivan Miric.
:license: MIT, see LICENSE for more details.
"""
import os
import os.path
import codecs
2022-01-27 19:43:10 +01:00
import sass
from flask import send_from_directory
2018-05-09 19:35:36 +02:00
2022-01-27 19:43:10 +01:00
def _convert(dir_path, src, dst):
2018-05-09 19:35:36 +02:00
original_wd = os.getcwd()
2022-01-27 19:43:10 +01:00
os.chdir(dir_path)
2018-05-09 19:35:36 +02:00
source = codecs.open(src, 'r', encoding='utf-8').read()
2022-01-27 19:43:10 +01:00
output = sass.compile(string=source)
2018-05-09 19:35:36 +02:00
os.chdir(original_wd)
outfile = codecs.open(dst, 'w', encoding='utf-8')
outfile.write(output)
outfile.close()
2022-01-27 19:43:10 +01:00
def _get_dir_path(app, original_path, create=False):
path = original_path
2018-05-09 19:35:36 +02:00
if not os.path.isdir(path):
path = os.path.join(app.root_path, path)
if not os.path.isdir(path):
if create:
os.mkdir(path)
else:
2022-01-27 19:43:10 +01:00
raise IOError("Unable to find " + original_path)
2018-05-09 19:35:36 +02:00
return path
2022-01-27 19:43:10 +01:00
def init_app(app, input_dir='scss', dest='static', force=False, cache_dir="public/static"):
input_dir = _get_dir_path(app, input_dir)
cache_dir = _get_dir_path(app, cache_dir or dest, True)
2018-05-09 19:35:36 +02:00
def _sass(filepath):
2022-01-27 19:43:10 +01:00
scss_file = "%s/%s.scss" % (input_dir, filepath)
cache_file = "%s/%s.css" % (cache_dir, filepath)
2018-05-09 19:35:36 +02:00
# Source file exists, and needs regenerating
2022-01-27 19:43:10 +01:00
if os.path.isfile(scss_file) and (force or not os.path.isfile(cache_file) or
os.path.getmtime(scss_file) > os.path.getmtime(cache_file)):
_convert(input_dir, scss_file, cache_file)
app.logger.debug('Compiled %s into %s' % (scss_file, cache_file))
2018-05-09 19:35:36 +02:00
2023-12-16 17:22:12 +01:00
res = send_from_directory(cache_dir, filepath + ".css")
res.headers["Cache-Control"] = "max-age=604800" # 1 week
return res
2018-05-09 19:35:36 +02:00
2022-01-27 19:43:10 +01:00
app.add_url_rule("/%s/<path:filepath>.css" % dest, 'sass', _sass)