better scss

This commit is contained in:
thomas girod 2024-07-26 15:14:37 +02:00
parent 594776f3a6
commit 424639ea80
10 changed files with 37 additions and 71 deletions

View File

@ -21,7 +21,6 @@
# #
# #
from pathlib import Path
from django.conf import settings from django.conf import settings
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
@ -33,7 +32,7 @@ class Command(BaseCommand):
help = "Output the fully rendered SYNTAX.md file" help = "Output the fully rendered SYNTAX.md file"
def handle(self, *args, **options): def handle(self, *args, **options):
root_path = Path(settings.BASE_DIR) root_path = settings.BASE_DIR
with open(root_path / "core/fixtures/SYNTAX.md", "r") as md: with open(root_path / "core/fixtures/SYNTAX.md", "r") as md:
result = markdown(md.read()) result = markdown(md.read())
print(result, end="") print(result, end="")

View File

@ -27,6 +27,7 @@ import importlib
import os import os
import unicodedata import unicodedata
from datetime import date, timedelta from datetime import date, timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Optional from typing import TYPE_CHECKING, Optional
from django.conf import settings from django.conf import settings
@ -56,8 +57,6 @@ from django.utils.html import escape
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from phonenumber_field.modelfields import PhoneNumberField from phonenumber_field.modelfields import PhoneNumberField
from core import utils
if TYPE_CHECKING: if TYPE_CHECKING:
from club.models import Club from club.models import Club
@ -377,7 +376,9 @@ class User(AbstractBaseUser):
USERNAME_FIELD = "username" USERNAME_FIELD = "username"
def promo_has_logo(self): def promo_has_logo(self):
return utils.file_exist("./core/static/core/img/promo_%02d.png" % self.promo) return Path(
settings.BASE_DIR / f"core/static/core/img/promo_{self.promo}.png"
).exists()
def has_module_perms(self, package_name): def has_module_perms(self, package_name):
return self.is_active return self.is_active

View File

@ -22,7 +22,6 @@
# #
# #
import os
from collections import OrderedDict from collections import OrderedDict
from django.conf import settings from django.conf import settings
@ -37,7 +36,7 @@ class ScssFinder(FileSystemFinder):
def __init__(self, apps=None, *args, **kwargs): def __init__(self, apps=None, *args, **kwargs):
location = settings.STATIC_ROOT location = settings.STATIC_ROOT
if not os.path.isdir(location): if not location.is_dir():
return return
self.locations = [("", location)] self.locations = [("", location)]
self.storages = OrderedDict() self.storages = OrderedDict()

View File

@ -21,61 +21,35 @@
# Place - Suite 330, Boston, MA 02111-1307, USA. # Place - Suite 330, Boston, MA 02111-1307, USA.
# #
# #
import functools
import os from pathlib import Path
from urllib.parse import urljoin
import sass import sass
from django.conf import settings from django.conf import settings
from django.core.files.base import ContentFile from django.core.files.base import ContentFile
from django.templatetags.static import static from django.templatetags.static import static
from django.utils.encoding import force_bytes, iri_to_uri from django_jinja.builtins.filters import static
from core.scss.storage import ScssFileStorage, find_file from core.scss.storage import ScssFileStorage, find_file
class ScssProcessor(object): @functools.cache
"""If DEBUG mode enabled : compile the scss file def _scss_storage():
Else : give the path of the corresponding css supposed to already be compiled return ScssFileStorage()
Don't forget to use compilestatics to compile scss for production.
"""
prefix = iri_to_uri(getattr(settings, "STATIC_URL", "/static/"))
storage = ScssFileStorage()
scss_extensions = [".scss"]
def __init__(self, path=None): def process_scss_path(path: Path):
self.path = path css_path = path.with_suffix(".css")
if settings.DEBUG:
def _convert_scss(self):
basename, ext = os.path.splitext(self.path)
css_filename = self.path.replace(".scss", ".css")
url = urljoin(self.prefix, css_filename)
if not settings.DEBUG:
return url
if ext not in self.scss_extensions:
return static(self.path)
# Compilation on the fly
compile_args = { compile_args = {
"filename": find_file(self.path), "filename": find_file(path),
"include_paths": settings.SASS_INCLUDE_FOLDERS, "include_paths": settings.SASS_INCLUDE_FOLDERS,
} }
if settings.SASS_PRECISION: if settings.SASS_PRECISION:
compile_args["precision"] = settings.SASS_PRECISION compile_args["precision"] = settings.SASS_PRECISION
content = sass.compile(**compile_args) content = sass.compile(**compile_args)
content = force_bytes(content) storage = _scss_storage()
if storage.exists(css_path):
if self.storage.exists(css_filename): storage.delete(css_path)
self.storage.delete(css_filename) storage.save(css_path, ContentFile(content))
self.storage.save(css_filename, ContentFile(content)) return static(css_path)
return url
def get_converted_scss(self):
if self.path:
return self._convert_scss()
else:
return ""

View File

@ -23,15 +23,17 @@
# #
import datetime import datetime
from pathlib import Path
import phonenumbers import phonenumbers
from django import template from django import template
from django.template import TemplateSyntaxError
from django.template.defaultfilters import stringfilter from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils.translation import ngettext from django.utils.translation import ngettext
from core.markdown import markdown as md from core.markdown import markdown as md
from core.scss.processor import ScssProcessor from core.scss.processor import process_scss_path
register = template.Library() register = template.Library()
@ -86,5 +88,7 @@ def format_timedelta(value: datetime.timedelta) -> str:
@register.simple_tag() @register.simple_tag()
def scss(path): def scss(path):
"""Return path of the corresponding css file after compilation.""" """Return path of the corresponding css file after compilation."""
processor = ScssProcessor(path) path = Path(path)
return processor.get_converted_scss() if path.suffix != ".scss":
raise TemplateSyntaxError("`scss` tag has been called with a non-scss file")
return process_scss_path(path)

View File

@ -14,7 +14,6 @@
# #
from datetime import date, timedelta from datetime import date, timedelta
from pathlib import Path
from smtplib import SMTPException from smtplib import SMTPException
import freezegun import freezegun
@ -210,7 +209,7 @@ def test_custom_markdown_syntax(md, html):
def test_full_markdown_syntax(): def test_full_markdown_syntax():
syntax_path = Path(settings.BASE_DIR) / "core" / "fixtures" syntax_path = settings.BASE_DIR / "core" / "fixtures"
md = (syntax_path / "SYNTAX.md").read_text() md = (syntax_path / "SYNTAX.md").read_text()
html = (syntax_path / "SYNTAX.html").read_text() html = (syntax_path / "SYNTAX.html").read_text()
result = markdown(md) result = markdown(md)

View File

@ -13,7 +13,6 @@
# #
# #
import os
import re import re
import subprocess import subprocess
from datetime import date from datetime import date
@ -96,10 +95,6 @@ def get_semester_code(d: Optional[date] = None) -> str:
return "P" + str(start.year)[-2:] return "P" + str(start.year)[-2:]
def file_exist(path):
return os.path.exists(path)
def scale_dimension(width, height, long_edge): def scale_dimension(width, height, long_edge):
if width > height: if width > height:
ratio = long_edge * 1.0 / width ratio = long_edge * 1.0 / width

View File

@ -59,17 +59,17 @@ def send_file(request, file_id, file_class=SithFile, file_attr="file"):
): ):
raise PermissionDenied raise PermissionDenied
name = f.__getattribute__(file_attr).name name = f.__getattribute__(file_attr).name
filepath = os.path.join(settings.MEDIA_ROOT, name) filepath = settings.MEDIA_ROOT / name
# check if file exists on disk # check if file exists on disk
if not os.path.exists(filepath.encode("utf-8")): if not filepath.exists():
raise Http404() raise Http404
with open(filepath.encode("utf-8"), "rb") as filename: with open(filepath, "rb") as filename:
wrapper = FileWrapper(filename) wrapper = FileWrapper(filename)
response = HttpResponse(wrapper, content_type=f.mime_type) response = HttpResponse(wrapper, content_type=f.mime_type)
response["Last-Modified"] = http_date(f.date.timestamp()) response["Last-Modified"] = http_date(f.date.timestamp())
response["Content-Length"] = os.path.getsize(filepath.encode("utf-8")) response["Content-Length"] = filepath.stat().st_size
response["Content-Disposition"] = ('inline; filename="%s"' % f.name).encode( response["Content-Disposition"] = ('inline; filename="%s"' % f.name).encode(
"utf-8" "utf-8"
) )

View File

@ -13,7 +13,6 @@
# #
# #
import os
from io import BytesIO from io import BytesIO
from django.conf import settings from django.conf import settings
@ -46,9 +45,7 @@ class Picture(SithFile):
@property @property
def is_vertical(self): def is_vertical(self):
with open( with open(settings.MEDIA_ROOT / self.file.name, "rb") as f:
os.path.join(settings.MEDIA_ROOT, self.file.name).encode("utf-8"), "rb"
) as f:
im = Image.open(BytesIO(f.read())) im = Image.open(BytesIO(f.read()))
(w, h) = im.size (w, h) = im.size
return (w / h) < 1 return (w / h) < 1
@ -112,9 +109,7 @@ class Picture(SithFile):
def rotate(self, degree): def rotate(self, degree):
for attr in ["file", "compressed", "thumbnail"]: for attr in ["file", "compressed", "thumbnail"]:
name = self.__getattribute__(attr).name name = self.__getattribute__(attr).name
with open( with open(settings.MEDIA_ROOT / name, "r+b") as file:
os.path.join(settings.MEDIA_ROOT, name).encode("utf-8"), "r+b"
) as file:
if file: if file:
im = Image.open(BytesIO(file.read())) im = Image.open(BytesIO(file.read()))
file.seek(0) file.seek(0)

View File

@ -46,7 +46,7 @@ from sentry_sdk.integrations.django import DjangoIntegration
from .honeypot import custom_honeypot_error from .honeypot import custom_honeypot_error
BASE_DIR = Path(".").parent.parent BASE_DIR = Path(__file__).parent.parent
os.environ["HTTPS"] = "off" os.environ["HTTPS"] = "off"