~tribaal/txaws/xss-hardening

« back to all changes in this revision

Viewing changes to txaws/server/registry.py

merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from txaws.server.exception import APIError
 
2
 
 
3
 
 
4
class Registry(object):
 
5
    """Register API L{Method}s. for handling specific actions and versions"""
 
6
 
 
7
    def __init__(self):
 
8
        self._by_action = {}
 
9
 
 
10
    def add(self, method_class, action, version=None):
 
11
        """Add a method class to the regitry.
 
12
 
 
13
        @param method_class: The method class to add
 
14
        @param action: The action that the method class can handle
 
15
        @param version: The version that the method class can handle
 
16
        """
 
17
        by_version = self._by_action.setdefault(action, {})
 
18
        if version in by_version:
 
19
            raise RuntimeError("A method was already registered for action"
 
20
                               " %s in version %s" % (action, version))
 
21
        by_version[version] = method_class
 
22
 
 
23
    def check(self, action, version=None):
 
24
        """Check if the given action is supported in the given version.
 
25
 
 
26
        @raises APIError: If there's no method class registered for handling
 
27
            the given action or version.
 
28
        """
 
29
        if action not in self._by_action:
 
30
            raise APIError(400, "InvalidAction", "The action %s is not valid "
 
31
                           "for this web service." % action)
 
32
        by_version = self._by_action[action]
 
33
        if None not in by_version:
 
34
            # There's no catch-all method, let's try the version-specific one
 
35
            if version not in by_version:
 
36
                raise APIError(400, "InvalidVersion", "Invalid API version.")
 
37
 
 
38
    def get(self, action, version=None):
 
39
        """Get the method class handing the given action and version."""
 
40
        by_version = self._by_action[action]
 
41
        if version in by_version:
 
42
            return by_version[version]
 
43
        else:
 
44
            return by_version[None]
 
45
 
 
46
    def scan(self, module, onerror=None):
 
47
        """Scan the given module object for L{Method}s and register them."""
 
48
        from venusian import Scanner
 
49
        scanner = Scanner(registry=self)
 
50
        scanner.scan(module, onerror=onerror)