From 320feb91796f2eba538eef48c338fb37ade980d2 Mon Sep 17 00:00:00 2001 From: Kevin Chung Date: Fri, 10 Apr 2020 12:50:55 -0400 Subject: [PATCH] Re-enable the Jinja LRU Cache (#1308) * Re-enable the Jinja LRU Cache by overriding the `Environment._load_template` function and adding a theme namespace --- CTFd/__init__.py | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/CTFd/__init__.py b/CTFd/__init__.py index b922a7c..4caf2cd 100644 --- a/CTFd/__init__.py +++ b/CTFd/__init__.py @@ -1,6 +1,7 @@ import datetime import os import sys +import weakref from distutils.version import StrictVersion from flask import Flask, Request @@ -71,11 +72,33 @@ class SandboxedBaseEnvironment(SandboxedEnvironment): def __init__(self, app, **options): if "loader" not in options: options["loader"] = app.create_global_jinja_loader() - # Disable cache entirely so that themes can be switched (#662) - # If the cache is enabled, switching themes will cause odd rendering errors - SandboxedEnvironment.__init__(self, cache_size=0, **options) + SandboxedEnvironment.__init__(self, **options) self.app = app + def _load_template(self, name, globals): + if self.loader is None: + raise TypeError("no loader for this environment specified") + + # Add theme to the LRUCache cache key + cache_name = name + if name.startswith("admin/") is False: + theme = str(utils.get_config("ctf_theme")) + cache_name = theme + "/" + name + + # Rest of this code is copied from Jinja + # https://github.com/pallets/jinja/blob/master/src/jinja2/environment.py#L802-L815 + cache_key = (weakref.ref(self.loader), cache_name) + if self.cache is not None: + template = self.cache.get(cache_key) + if template is not None and ( + not self.auto_reload or template.is_up_to_date + ): + return template + template = self.loader.load(self, name, globals) + if self.cache is not None: + self.cache[cache_key] = template + return template + class ThemeLoader(FileSystemLoader): """Custom FileSystemLoader that switches themes based on the configuration value"""