More documentation

This commit is contained in:
Gina Häußge committed 2015-02-27 20:28:24 +01:00
1 parent 84c32a3cd9
commit cd3ead3f30
12 files changed
+712 -75

No files matched your search

+173 -12
View File
@@ -1,4 +1,19 @@
# coding=utf-8
"""
This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the
registered plugin types.
.. autofunction:: plugin_manager
.. autofunction:: plugin_settings
.. autofunction:: call_plugin
.. autoclass:: PluginSettings
:members:
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
@@ -18,9 +33,41 @@ from octoprint.util import deprecated
_instance = None
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
Arguments:
init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not
(False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError`
will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to
False.
plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for
potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and
``src/plugins`` within OctoPrint's code base.
plugin_types (list): A list of recognized plugin types for which to look for provided implementations. If not
provided this defaults to the plugin types found in :mod:`octoprint.plugin.types` without
:class:`~octoprint.plugin.OctoPrintPlugin`.
plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided
this defaults to the entry point ``octoprint.plugin``.
plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this
defaults to all plugins for which ``enabled`` is set to ``False`` in the settings.
Returns:
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
management tasks.
Raises:
ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although
the plugin manager was not yet initialized.
"""
global _instance
if _instance is None:
if init:
if _instance is not None:
raise ValueError("Plugin Manager already initialized")
if plugin_folders is None:
plugin_folders = (settings().getBaseFolder("plugins"), os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")))
if plugin_types is None:
@@ -51,10 +98,59 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
def plugin_settings(plugin_key, defaults=None):
"""
Factory method for creating a :class:`PluginSettings` instance.
Arguments:
plugin_key (string): The plugin identifier for which to create the settings instance.
defaults (dict): The default settings for the plugin.
Returns:
PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's
settings
"""
return PluginSettings(settings(), plugin_key, defaults=defaults)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
and/or failure of each call which can be used to return individual results to the calling code.
Example:
.. sourcecode:: python
def my_success_callback(name, plugin, result):
print("{name} was called successfully and returned {result!r}".format(**locals()))
def my_error_callback(name, plugin, exc):
print("{name} raised an exception: {exc!s}".format(**locals()))
octoprint.plugin.call_plugin(
[octoprint.plugin.StartupPlugin],
"on_startup",
args=(my_host, my_port),
callback=my_success_callback,
error_callback=my_error_callback
)
Arguments:
types (list): A list of plugin implementation types to match against.
method (string): Name of the method to call on all matching implementations.
args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional.
kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional.
callback (function): A callback to invoke after an implementation has been called successfully. Will be called
with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier,
``plugin`` the plugin implementation instance itself and ``result`` the result returned from the
``method`` invocation.
error_callback (function): A callback to invoke after the call of an implementation resulted in an exception.
Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
"""
if not isinstance(types, (list, tuple)):
types = [types]
if args is None:
@@ -69,14 +165,53 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(name, plugin, result)
except Exception as e:
except Exception as exc:
logging.getLogger(__name__).exception("Error while calling plugin %s" % name)
if error_callback:
error_callback(name, plugin, e)
error_callback(name, plugin, exc)
class PluginSettings(object):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
It provides a couple of convenience methods for directly accessing plugin settings via the regular
:class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations.
.. method:: get(path, merged=False, asdict=False)
Retrieves a raw key from the settings for ``path``, optionally merging the raw value with the default settings
if ``merged`` is set to True.
:param list path: a list of path elements to navigate to the settings value
:param boolean merged: whether to merge the returned result with the default settings (True) or not (False, default)
:return: the retrieved settings value
.. method:: get_int(path)
.. method:: get_float(path)
.. method:: get_boolean(path)
.. method:: set(path, value, force=False)
.. method:: set_int(path, value, force=False)
.. method:: set_float(path, value, force=False)
.. method:: set_boolean(path, value, force=False)
"""
def __init__(self, settings, plugin_key, defaults=None):
"""
Initializes the object with the provided :class:`octoprint.settings.Settings` manager as ``settings``, using
the ``plugin_key`` and optional ``defaults``.
:param settings:
:param plugin_key:
:param defaults:
:return:
"""
self.settings = settings
self.plugin_key = plugin_key
@@ -119,39 +254,30 @@ class PluginSettings(object):
def global_get(self, path, **kwargs):
return self.settings.get(path, **kwargs)
globalGet = deprecated("globalGet has been renamed to global_get")(global_get)
def global_get_int(self, path, **kwargs):
return self.settings.getInt(path, **kwargs)
globalGetInt = deprecated("globalGetInt has been renamed to global_get_int")(global_get_int)
def global_get_float(self, path, **kwargs):
return self.settings.getFloat(path, **kwargs)
globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float")(global_get_float)
def global_get_boolean(self, path, **kwargs):
return self.settings.getBoolean(path, **kwargs)
globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean")(global_get_boolean)
def global_set(self, path, value, **kwargs):
self.settings.set(path, value, **kwargs)
globalSet = deprecated("globalSet has been renamed to global_set")(global_set)
def global_set_int(self, path, value, **kwargs):
self.settings.setInt(path, value, **kwargs)
globalSetInt = deprecated("globalSetInt has been renamed to global_set_int")(global_set_int)
def global_set_float(self, path, value, **kwargs):
self.settings.setFloat(path, value, **kwargs)
globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float")(global_set_float)
def global_set_boolean(self, path, value, **kwargs):
self.settings.setBoolean(path, value, **kwargs)
globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean")(global_set_boolean)
def global_get_basefolder(self, folder_type, **kwargs):
return self.settings.getBaseFolder(folder_type, **kwargs)
globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder")(global_get_basefolder)
def get_plugin_logfile_path(self, postfix=None):
filename = "plugin_" + self.plugin_key
@@ -159,7 +285,6 @@ class PluginSettings(object):
filename += "_" + postfix
filename += ".log"
return os.path.join(self.settings.getBaseFolder("logs"), filename)
getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path")(get_plugin_logfile_path)
def __getattr__(self, item):
all_access_methods = self.access_methods.keys() + self.deprecated_access_methods.keys()
@@ -179,7 +304,43 @@ class PluginSettings(object):
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = item
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
return _func
return getattr(self.settings, item)
##~~ deprecated methods follow
# TODO: Remove with release of 1.2.0
globalGet = deprecated("globalGet has been renamed to global_get",
includedoc="Replaced by :func:`global_get`",
since="1.2.0-dev-546")(global_get)
globalGetInt = deprecated("globalGetInt has been renamed to global_get_int",
includedoc="Replaced by :func:`global_get_int`",
since="1.2.0-dev-546")(global_get_int)
globalGetFloat = deprecated("globalGetFloat has been renamed to global_get_float",
includedoc="Replaced by :func:`global_get_float`",
since="1.2.0-dev-546")(global_get_float)
globalGetBoolean = deprecated("globalGetBoolean has been renamed to global_get_boolean",
includedoc="Replaced by :func:`global_get_boolean`",
since="1.2.0-dev-546")(global_get_boolean)
globalSet = deprecated("globalSet has been renamed to global_set",
includedoc="Replaced by :func:`global_set`",
since="1.2.0-dev-546")(global_set)
globalSetInt = deprecated("globalSetInt has been renamed to global_set_int",
includedoc="Replaced by :func:`global_set_int`",
since="1.2.0-dev-546")(global_set_int)
globalSetFloat = deprecated("globalSetFloat has been renamed to global_set_float",
includedoc="Replaced by :func:`global_set_float`",
since="1.2.0-dev-546")(global_set_float)
globalSetBoolean = deprecated("globalSetBoolean has been renamed to global_set_boolean",
includedoc="Replaced by :func:`global_set_boolean`",
since="1.2.0-dev-546")(global_set_boolean)
globalGetBaseFolder = deprecated("globalGetBaseFolder has been renamed to global_get_basefolder",
includedoc="Replaced by :func:`global_get_basefolder`",
since="1.2.0-dev-546")(global_get_basefolder)
getPluginLogfilePath = deprecated("getPluginLogfilePath has been renamed to get_plugin_logfile_path",
includedoc="Replaced by :func:`get_plugin_logfile_path`",
since="1.2.0-dev-546")(get_plugin_logfile_path)
+56
View File
@@ -1,4 +1,16 @@
# coding=utf-8
"""
In this module resides the core data structures and logic of the plugin system. It is implemented in an OctoPrint-agnostic
way and could be extracted into a separate Python module in the future.
.. autoclass:: PluginManager
.. autoclass:: PluginInfo
.. autoclass:: Plugin
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
@@ -13,6 +25,15 @@ import logging
class PluginInfo(object):
"""
The :class:`PluginInfo` class wraps all available information about a registered plugin.
This includes its meta data (like name, description, version, etc) as well as the actual plugin extensions like
implementations, hooks and helpers.
It works on Python module objects and extracts the relevant data from those via accessing the
:ref:`control properties <sec-plugins-infrastructure-controlproperties>`.
"""
attr_name = '__plugin_name__'
@@ -125,6 +146,12 @@ class PluginInfo(object):
class PluginManager(object):
"""
The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the
system.
It is able to discover plugins both through possible file system locations as well as customizable entry points.
"""
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None):
self.logger = logging.getLogger(__name__)
@@ -405,5 +432,34 @@ class PluginManager(object):
class Plugin(object):
"""
The parent class of all plugin implementations.
.. attribute:: _identifier
The identifier of the plugin. Injected by the plugin core system upon initialization of the implementation.
.. attribute:: _plugin_name
The name of the plugin. Injected by the plugin core system upon initialization of the implementation.
.. attribute:: _plugin_version
The version of the plugin. Injected by the plugin core system upon initialization of the implementation.
.. attribute:: _basefolder
The base folder of the plugin. Injected by the plugin core system upon initialization of the implementation.
.. attribute:: _logger
The logger instance to use, with the logging name set to the :attr:`PluginManager.logging_prefix` of the
:class:`PluginManager` concatenated with :attr:`_identifier`. Injected by the plugin core system upon
initialization of the implementation.
"""
def initialize(self):
"""
Called by the plugin core after performing all injections.
"""
pass
+53 -15
View File
@@ -1,4 +1,15 @@
# coding=utf-8
"""
This module bundles all of OctoPrint's supported plugin implementation types as well as their common parent
class, :class:`OctoPrintPlugin`.
Please note that the plugin implementation types are documented in the section
:ref:`Available plugin mixins <sec-plugins-mixins>`.
.. autoclass: OctoPrintPlugin
"""
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
@@ -9,7 +20,29 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .core import Plugin
class StartupPlugin(Plugin):
class OctoPrintPlugin(Plugin):
"""
.. attribute:: _plugin_manager
.. attribute:: _printer_profile_manager
.. attribute:: _event_bus
.. attribute:: _analysis_queue
.. attribute:: _slicing_manager
.. attribute:: _file_manager
.. attribute:: _printer
.. attribute:: _app_session_manager
"""
pass
class StartupPlugin(OctoPrintPlugin):
"""
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
on or just after the startup of the server.
@@ -37,7 +70,7 @@ class StartupPlugin(Plugin):
pass
class ShutdownPlugin(Plugin):
class ShutdownPlugin(OctoPrintPlugin):
"""
The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the
:class:`StartupPlugin` mixin, to cleanly shut down additional services again that where started by the :class:`StartupPlugin`
@@ -51,14 +84,14 @@ class ShutdownPlugin(Plugin):
pass
class AssetPlugin(Plugin):
class AssetPlugin(OctoPrintPlugin):
"""
The ``AssetPlugin`` mixin allows plugins to define additional static assets such as Javascript or CSS files to
be automatically embedded into the pages delivered by the server to be used within the client sided part of
the plugin.
A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected
through :class:`TemplatePlugin`s.
through a :class:`TemplatePlugin`.
"""
def get_asset_folder(self):
@@ -104,7 +137,7 @@ class AssetPlugin(Plugin):
return dict()
class TemplatePlugin(Plugin):
class TemplatePlugin(OctoPrintPlugin):
"""
Using the ``TemplatePlugin`` mixin plugins may inject their own components into the OctoPrint web interface.
@@ -408,7 +441,7 @@ class TemplatePlugin(Plugin):
return os.path.join(self._basefolder, "templates")
class SimpleApiPlugin(Plugin):
class SimpleApiPlugin(OctoPrintPlugin):
"""
Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one
resource accepting JSON commands POSTed to it. This is the easy alternative for plugin's which don't need the
@@ -543,7 +576,7 @@ class SimpleApiPlugin(Plugin):
return None
class BlueprintPlugin(Plugin):
class BlueprintPlugin(OctoPrintPlugin):
"""
The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose,
be it a more sophisticated API than what is possible via the :class:`SimpleApiPlugin` or a custom web frontend.
@@ -646,7 +679,7 @@ class BlueprintPlugin(Plugin):
return True
class SettingsPlugin(Plugin):
class SettingsPlugin(OctoPrintPlugin):
"""
Including the ``SettingsPlugin`` mixin allows plugins to store and retrieve their own settings within OctoPrint's
configuration.
@@ -697,6 +730,11 @@ class SettingsPlugin(Plugin):
Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the
default implementations do not fit your requirements.
.. attribute:: _settings
The :class:`~octoprint.plugin.PluginSettings` instance to use for accessing the plugin's settings. Injected by
the plugin core system upon initialization of the implementation.
"""
def on_settings_load(self):
@@ -751,7 +789,7 @@ class SettingsPlugin(Plugin):
return dict()
class EventHandlerPlugin(Plugin):
class EventHandlerPlugin(OctoPrintPlugin):
"""
The ``EventHandlerPlugin`` mixin allows OctoPrint plugins to react to any of :ref:`OctoPrint's events <sec-events>`.
OctoPrint will call the :func:`on_event` method for any event fired on its internal event bus, supplying the
@@ -774,7 +812,7 @@ class EventHandlerPlugin(Plugin):
pass
class SlicerPlugin(Plugin):
class SlicerPlugin(OctoPrintPlugin):
"""
Via the ``SlicerPlugin`` mixin plugins can add support for slicing engines to be used by OctoPrint.
@@ -835,10 +873,10 @@ class SlicerPlugin(Plugin):
``False`` (defaults to ``True``), an ``IOError`` should be raised.
:param string path: the path to which to save the profile
:param :class:`SlicingProfile` profile: the profile to save
:param SlicingProfile profile: the profile to save
:param bool allow_overwrite: whether to allow to overwrite an existing profile at the indicated path (``True``, default)
or not (``False``) - if a profile already exists on the path and this is ``False``
and :class:`IOError` should be raised
or not (``False``) - if a profile already exists on the path and this is ``False``
and :class:`IOError` should be raised
:param dict overrides: profile overrides to apply to the ``profile`` before saving it
"""
pass
@@ -881,7 +919,7 @@ class SlicerPlugin(Plugin):
pass
class ProgressPlugin(Plugin):
class ProgressPlugin(OctoPrintPlugin):
"""
Via the ``ProgressPlugin`` mixing plugins can let themselves be called upon progress in print jobs or slicing jobs,
limited to minimally 1% steps.
@@ -911,7 +949,7 @@ class ProgressPlugin(Plugin):
pass
class AppPlugin(Plugin):
class AppPlugin(OctoPrintPlugin):
def get_additional_apps(self):
return []