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
bulk-clear-sessions
Kevin Chung 2020-04-10 12:50:55 -04:00 committed by GitHub
parent 1249229faf
commit 320feb9179
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 26 additions and 3 deletions

View File

@ -1,6 +1,7 @@
import datetime import datetime
import os import os
import sys import sys
import weakref
from distutils.version import StrictVersion from distutils.version import StrictVersion
from flask import Flask, Request from flask import Flask, Request
@ -71,11 +72,33 @@ class SandboxedBaseEnvironment(SandboxedEnvironment):
def __init__(self, app, **options): def __init__(self, app, **options):
if "loader" not in options: if "loader" not in options:
options["loader"] = app.create_global_jinja_loader() options["loader"] = app.create_global_jinja_loader()
# Disable cache entirely so that themes can be switched (#662) SandboxedEnvironment.__init__(self, **options)
# If the cache is enabled, switching themes will cause odd rendering errors
SandboxedEnvironment.__init__(self, cache_size=0, **options)
self.app = app 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): class ThemeLoader(FileSystemLoader):
"""Custom FileSystemLoader that switches themes based on the configuration value""" """Custom FileSystemLoader that switches themes based on the configuration value"""