Source

django-awesomebox / awesomebox / base.py

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(
                False,
                ('Invalid result type given. Expected '
                 'awesomebox.base.Result instance.'),
            )
        return result

    def notify_user(self, request, result):
        ''' Default method to notify the user of success. Override
            to customize
        '''
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            from django.contrib import messages
            level = messages.SUCCESS if result.success else messages.ERROR
            messages.add_message(request, level, result.message)

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


class NullAwesomeBox(BaseAwesomebox):
    pass


def get_awesomebox_class():
    ''' Return the class to use for Awesomebox dispatching.
    '''
    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 '
            'awesomebox.base.BaseAwesomebox'
        )
    return cls
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.