django-orchestra-test/orchestra/plugins/options.py

79 lines
2.4 KiB
Python
Raw Normal View History

2014-11-12 16:33:40 +00:00
from orchestra.utils.functional import cached
2014-07-21 12:20:04 +00:00
class Plugin(object):
verbose_name = None
2014-10-11 12:43:08 +00:00
# Used on select plugin view
class_verbose_name = None
icon = None
2014-07-21 12:20:04 +00:00
@classmethod
2014-11-12 16:33:40 +00:00
def get_name(cls):
2014-07-21 12:20:04 +00:00
return cls.__name__
@classmethod
def get_plugins(cls):
return cls.plugins
@classmethod
@cached
def get_plugin(cls, name):
for plugin in cls.get_plugins():
2014-11-12 16:33:40 +00:00
if plugin.get_name() == name:
2014-07-21 12:20:04 +00:00
return plugin
raise KeyError('This plugin is not registered')
2014-10-11 16:21:51 +00:00
@classmethod
def get_verbose_name(cls):
# don't evaluate p.verbose_name ugettext_lazy
verbose = getattr(cls.verbose_name, '_proxy____args', [cls.verbose_name])
if verbose[0]:
return cls.verbose_name
else:
2014-11-12 16:33:40 +00:00
return cls.get_name()
2014-10-11 16:21:51 +00:00
2014-07-21 12:20:04 +00:00
@classmethod
def get_plugin_choices(cls):
choices = []
2014-10-11 16:21:51 +00:00
for plugin in cls.get_plugins():
verbose = plugin.get_verbose_name()
2014-11-12 16:33:40 +00:00
choices.append((plugin.get_name(), verbose))
2014-10-11 16:21:51 +00:00
return sorted(choices, key=lambda e: e[1])
2014-07-21 12:20:04 +00:00
2014-11-13 15:34:00 +00:00
class PluginModelAdapter(Plugin):
""" Adapter class for using model classes as plugins """
model = None
name_field = None
@classmethod
def get_plugins(cls):
plugins = []
for instance in cls.model.objects.filter(is_active=True):
attributes = {
'instance': instance,
'verbose_name': instance.verbose_name
}
plugins.append(type('PluginAdapter', (cls,), attributes))
return plugins
@classmethod
def get_name(cls):
return getattr(cls.instance, cls.name_field)
2014-05-08 16:59:35 +00:00
class PluginMount(type):
def __init__(cls, name, bases, attrs):
2014-10-11 16:21:51 +00:00
if not attrs.get('abstract', False):
if not hasattr(cls, 'plugins'):
# This branch only executes when processing the mount point itself.
# So, since this is a new plugin type, not an implementation, this
# class shouldn't be registered as a plugin. Instead, it sets up a
# list where plugins can be registered later.
cls.plugins = []
else:
# This must be a plugin implementation, which should be registered.
# Simply appending it to the list is all that's needed to keep
# track of it later.
cls.plugins.append(cls)