Mercurial > piecrust2
comparison piecrust/plugins/base.py @ 848:7d83b9484b98
plugins: Add support for "ad-hoc" local plugins.
These are loose `.py` files inside of the `plugins` folder of a website.
They're loaded along with other normal (packaged) plugins.
author | Ludovic Chabant <ludovic@chabant.com> |
---|---|
date | Thu, 27 Apr 2017 20:54:29 -0700 |
parents | bf9f4e55f751 |
children | 8f8bbb2e70e1 |
comparison
equal
deleted
inserted
replaced
847:71c4f43d8fc1 | 848:7d83b9484b98 |
---|---|
1 import os.path | |
2 import sys | |
1 import logging | 3 import logging |
2 import importlib | 4 import importlib |
5 import importlib.util | |
3 | 6 |
4 | 7 |
5 logger = logging.getLogger(__name__) | 8 logger = logging.getLogger(__name__) |
6 | 9 |
7 | 10 |
111 | 114 |
112 for plugin in self._plugins: | 115 for plugin in self._plugins: |
113 plugin.initialize(self.app) | 116 plugin.initialize(self.app) |
114 | 117 |
115 def _loadPlugin(self, plugin_name): | 118 def _loadPlugin(self, plugin_name): |
119 mod_name = 'piecrust_%s' % plugin_name | |
116 try: | 120 try: |
117 mod = importlib.import_module('piecrust_' + plugin_name) | 121 # Import from the current environment. |
122 mod = importlib.import_module(mod_name) | |
118 except ImportError as ex: | 123 except ImportError as ex: |
124 mod = None | |
125 | |
126 if mod is None: | |
127 # Import as a loose Python file from the plugins dir. | |
128 pfile = os.path.join(self.app.plugins_dir, plugin_name + '.py') | |
129 if os.path.isfile(pfile): | |
130 spec = importlib.util.spec_from_file_location(plugin_name, | |
131 pfile) | |
132 mod = importlib.util.module_from_spec(spec) | |
133 spec.loader.exec_module(mod) | |
134 sys.modules[mod_name] = mod | |
135 | |
136 if mod is None: | |
119 logger.error("Failed to load plugin '%s'." % plugin_name) | 137 logger.error("Failed to load plugin '%s'." % plugin_name) |
120 logger.error(ex) | 138 logger.error(ex) |
121 return | 139 return |
122 | 140 |
123 plugin_class = getattr(mod, '__piecrust_plugin__', None) | 141 plugin_class = getattr(mod, '__piecrust_plugin__', None) |