♻ Improved implementation of #4281

Instead of forcing plugins to use absolute paths to templates,
via a plugin aware jinja2 environment it is now detected whether
the template they are importing does locally exist in their own
template folder (in which case it gets automatically prefixed) or not.

A deprecation notice is now only logged when a plugin imports a
template from another template without the prefix (which probably
is a *very* rare occurence anyhow).
This commit is contained in:
Gina Häußge committed 2021-10-28 16:05:20 +02:00
1 parent e293fd1c3e
commit 0438f77d71
9 files changed
+73 -37

No files matched your search

@@ -108,7 +108,7 @@
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
{% set plugin_backup_upload_form_id='settings-backup-upload' %}
{% include "plugin_backup/snippets/backup_plugin_upload_form.jinja2" %}
{% include "snippets/backup_plugin_upload_form.jinja2" %}
</div>
<div data-bind="visible: !restoreSupported()">
@@ -5,4 +5,4 @@
</p>{% endtrans %}
{% set plugin_backup_upload_form_id='wizard-backup-upload' %}
{% include "plugin_backup/snippets/backup_plugin_upload_form.jinja2" %}
{% include "snippets/backup_plugin_upload_form.jinja2" %}
@@ -158,11 +158,11 @@
</div>
<div class="modal-body">
<form class="form-horizontal" onsubmit="return false;">
{% include "plugin_softwareupdate/snippets/versionTracking.jinja2" %}
{% include "plugin_softwareupdate/snippets/trackedBranch.jinja2" %}
{% include "plugin_softwareupdate/snippets/checkoutFolder.jinja2" %}
{% include "plugin_softwareupdate/snippets/pipTarget.jinja2" %}
{% include "plugin_softwareupdate/snippets/pipEnableCheck.jinja2" %}
{% include "snippets/versionTracking.jinja2" %}
{% include "snippets/trackedBranch.jinja2" %}
{% include "snippets/checkoutFolder.jinja2" %}
{% include "snippets/pipTarget.jinja2" %}
{% include "snippets/pipEnableCheck.jinja2" %}
<div class="control-group">
<label class="control-label">{{ _('Version cache TTL') }}</label>
<div class="controls">
@@ -7,9 +7,9 @@
</p>{% endtrans %}
<form class="form-horizontal" onsubmit="return false;">
{% include "plugin_softwareupdate/snippets/versionTracking.jinja2" %}
{% include "plugin_softwareupdate/snippets/checkoutFolder.jinja2" %}
{% include "plugin_softwareupdate/snippets/trackedBranch.jinja2" %}
{% include "snippets/versionTracking.jinja2" %}
{% include "snippets/checkoutFolder.jinja2" %}
{% include "snippets/trackedBranch.jinja2" %}
</form>
{% trans %}<p>
@@ -1,6 +1,6 @@
<h3>{{ _('Anonymous Usage Tracking') }}</h3>
{% include "plugin_tracking/snippets/trackingDescription.jinja2" %}
{% include "snippets/trackingDescription.jinja2" %}
<form class="form-horizontal" onsubmit="return false;">
<div class="control-group">
@@ -59,4 +59,4 @@
</div>
</form>
{% include "plugin_tracking/snippets/trackingDetails.jinja2" %}
{% include "snippets/trackingDetails.jinja2" %}
@@ -1,8 +1,8 @@
<h3>{{ _('Configure Anonymous Usage Tracking') }}</h3>
{% include "plugin_tracking/snippets/trackingDescription.jinja2" %}
{% include "snippets/trackingDescription.jinja2" %}
{% include "plugin_tracking/snippets/trackingDetails.jinja2" %}
{% include "snippets/trackingDetails.jinja2" %}
<p>
{{ _('<strong>Note:</strong> You can always change your decision and also access more granular controls via Settings > Anonymous Usage Tracking.') }}
+14 -23
View File
@@ -258,9 +258,6 @@ class Server(object):
self._lifecycle_callbacks = defaultdict(list)
self._plugin_template_loader = None
self._plugin_template_fallback_loader = None
self._intermediary_server = None
def run(self):
@@ -1346,9 +1343,13 @@ class Server(object):
OctoPrintFlaskResponse,
OctoPrintJsonEncoder,
OctoPrintSessionInterface,
PrefixAwareJinjaEnvironment,
ReverseProxiedEnvironment,
)
# we must set this here because setting app.debug will access app.jinja_env
app.jinja_environment = PrefixAwareJinjaEnvironment
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False
@@ -1544,14 +1545,9 @@ class Server(object):
import octoprint.util.jinja
self._plugin_template_loader = jinja2.PrefixLoader({})
self._plugin_template_fallback_loader = (
octoprint.util.jinja.FilteredFileSystemLoader(
[], path_filter=lambda x: not octoprint.util.is_hidden_path(x)
)
)
app.jinja_env.prefix_loader = jinja2.PrefixLoader({})
loaders = [app.jinja_loader, self._plugin_template_loader]
loaders = [app.jinja_loader, app.jinja_env.prefix_loader]
if octoprint.util.is_running_from_source():
from markdown import markdown
@@ -1566,16 +1562,16 @@ class Server(object):
)
)
warning_message = "DeprecationWarning: Used relative path '{template}' to load/import plugin template '{filename}'. This is deprecated. You should switch to using paths with plugin prefix, e.g. 'plugin_example/{template}'"
# TODO: Remove this in 2.0.0
warning_message = "Loading plugin template '{template}' from '{filename}' without plugin prefix, this is deprecated and will soon no longer be supported."
loaders.append(
octoprint.util.jinja.WarningLoader(
self._plugin_template_fallback_loader,
octoprint.util.jinja.PrefixChoiceLoader(app.jinja_env.prefix_loader),
warning_message,
)
)
jinja_loader = jinja2.ChoiceLoader(loaders)
app.jinja_loader = jinja_loader
app.jinja_loader = jinja2.ChoiceLoader(loaders)
self._register_template_plugins()
@@ -1753,27 +1749,22 @@ class Server(object):
folder = plugin.get_template_folder()
if (
folder is not None
and plugin.template_folder_key not in self._plugin_template_loader.mapping
and plugin.template_folder_key not in app.jinja_env.prefix_loader.mapping
):
loader = octoprint.util.jinja.FilteredFileSystemLoader(
[plugin.get_template_folder()],
path_filter=lambda x: not octoprint.util.is_hidden_path(x),
)
self._plugin_template_loader.mapping[plugin.template_folder_key] = loader
self._plugin_template_fallback_loader.searchpath.append(folder)
app.jinja_env.prefix_loader.mapping[plugin.template_folder_key] = loader
def _unregister_additional_template_plugin(self, plugin):
folder = plugin.get_template_folder()
if (
folder is not None
and plugin.template_folder_key in self._plugin_template_loader.mapping
and plugin.template_folder_key in app.jinja_env.prefix_loader.mapping
):
del self._plugin_template_loader.mapping[plugin.template_folder_key]
try:
self._plugin_template_fallback_loader.searchpath.remove(folder)
except ValueError:
pass
del app.jinja_env.prefix_loader.mapping[plugin.template_folder_key]
def _setup_blueprints(self):
# do not remove or the index view won't be found
+31
View File
@@ -17,6 +17,7 @@ import time
import flask
import flask.json
import flask.sessions
import flask.templating
import flask_assets
import flask_login
import netaddr
@@ -602,6 +603,36 @@ class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
return super(OctoPrintSessionInterface, self).save_session(app, session, response)
# ~~ jinja environment
class PrefixAwareJinjaEnvironment(flask.templating.Environment):
def __init__(self, *args, **kwargs):
flask.templating.Environment.__init__(self, *args, **kwargs)
self.prefix_loader = None
self._cached_templates = {}
def join_path(self, template, parent):
if parent and "/" in parent:
prefix, _ = parent.split("/", 1)
if template in self._templates_for_prefix(prefix) and not template.startswith(
prefix + "/"
):
return prefix + "/" + template
return template
def _templates_for_prefix(self, prefix):
if prefix in self._cached_templates:
return self._cached_templates[prefix]
templates = []
if prefix in self.prefix_loader.mapping:
templates = self.prefix_loader.mapping[prefix].list_templates()
self._cached_templates[prefix] = templates
return templates
# ~~ passive login helper
_cached_local_networks = None
+14
View File
@@ -117,6 +117,20 @@ class SelectedFilesWithConversionLoader(SelectedFilesLoader):
return contents
class PrefixChoiceLoader(BaseLoader):
def __init__(self, loader):
self.loader = loader
def get_source(self, environment, template):
for prefix in sorted(self.loader.mapping.keys()):
try:
return self.loader.mapping[prefix].get_source(environment, template)
except TemplateNotFound:
pass
raise TemplateNotFound(template)
class WarningLoader(BaseLoader):
"""
Logs a warning if the loader is used to successfully load a template.