Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3from operator import itemgetter
4from superdjango.shortcuts import get_app_modules
6# Exports
8__all__ = (
9 "HookManager",
10)
12# Classes
15class HookManager(object):
16 """Serves as registry and interface for hooks."""
18 def __init__(self, module_name="hooks"):
19 """Initialize the hook manager.
21 :param module_name: The name of the module to look for hooks.
22 :type module_name:
24 """
25 self.hooks = dict()
27 self.is_loaded = False
28 self.module_name = module_name
30 def get(self, name):
31 """An alias for ``get_hooks()``."""
32 return self.get_hooks(name)
34 def get_hooks(self, name):
35 """Get the hooks defined for the named hook.
37 :param name: The name of the hook.
38 :type name: str
40 :rtype: list
41 :returns: A list of hooks (callables) for the given name.
43 """
44 self.load()
46 _hooks = self.hooks.get(name, list())
47 _hooks = sorted(_hooks, key=itemgetter(1))
49 return [hook[0] for hook in _hooks]
51 def load(self):
52 """Load hook modules if not already loaded."""
53 if not self.is_loaded:
54 list(get_app_modules(self.module_name))
55 self.is_loaded = True
57 def register(self, function, hook=None, sort_order=0):
58 """Register a function as a hook.
60 :param function: The function to call for the hook.
62 :param hook: The name of the hook. Defaults to the name of the function.
63 :type hook: str
65 :param sort_order: The order in which the function should be called.
66 :type sort_order: int
68 """
69 if hook is None:
70 hook = function.__name__
72 if hook not in self.hooks:
73 self.hooks[hook] = list()
75 self.hooks[hook].append((function, sort_order))