django-awesomebox / awesomebox /

from collections import namedtuple
from django.conf import settings
from django.utils.importlib import import_module
from django.core.urlresolvers import reverse_lazy

Result = namedtuple('Result', ['success', 'message'])

class BaseAwesomebox(object):
    init_str = '!'
    cmd_sep = ' '
    success_url = reverse_lazy('awesomebox_main')
    template_name = 'awesomebox/awesomebox.html'

    def __init__(self, cmd):
        self.cmd = cmd

    def run_command(self):
        cmd = self.cmd
        if self.init_str is not None and not cmd.startswith(self.init_str):
            return Result(False, 'Invalid command initialization.')

        real_cmd, _, data = cmd[len(self.init_str):].partition(self.cmd_sep)
        func = getattr(self, 'cmd_{}'.format(real_cmd, None)
        if func is None or not callable(func):
            return Result(False, 'Invalid command.')

        result = func(data)
        if not isinstance(result, Result):
            return Result(
                ('Invalid result type given. Expected '
                 'awesomebox.base.Result instance.'),
        return result

    def cmd_echo(self, data):
        ''' Example function. Returns back the data passed in.
        return Result(True, data)

def get_awesomebox_class():
    ''' Return the class to use for Awesomebox dispatching.
    class NullAwesomeBox(BaseAwesomebox):

    cls_path = getattr(settings, 'AWESOMEBOX_CLASS', None)
    cls = NullAwesomeBox if cls_path is None else import_module(cls_path)
    if not issubclass(cls, BaseAwesomebox):
        raise TypeError(
            'Invalid Awesomebox Class. Must subclass '
    return cls