1. Paul Tan
  2. cherrypy-regexdispatcher

Commits

Paul Tan  committed 543e077

Initial Commit

  • Participants
  • Branches default

Comments (0)

Files changed (1)

File cherrypyregexdispatcher.py

View file
  • Ignore whitespace
+import cherrypy._cpdispatch
+from cherrypy._cpdispatch import LateParamPageHandler
+
+class RegexDispatcher:
+       
+    def __init__(self, handlers = []):
+        """
+        handlers
+        (compiled_regex, handler)
+        """
+        self.handlers = handlers
+
+    def __call__(self, path_info):
+        """Set handler and config for the current request."""
+        request = cherrypy.serving.request
+        func, params = self.find_handler(path_info)
+        if func:
+            request.handler = LateParamPageHandler(func, **params)
+        else:
+            request.handler = cherrypy.NotFound()
+    
+    def find_handler(self, path):
+        """Return the appropriate page handler, plus any virtual path.
+        
+        This will return two objects. The first will be a callable,
+        which can be used to generate page output. Any parameters from
+        the query string or request body will be sent to that callable
+        as keyword arguments.
+        
+        The callable is found by traversing the application's tree,
+        starting from cherrypy.request.app.root, and matching path
+        components to successive objects in the tree. For example, the
+        URL "/path/to/handler" might return root.path.to.handler.
+        
+        The second object returned will be a list of names which are
+        'virtual path' components: parts of the URL which are dynamic,
+        and were not used when looking up the handler.
+        These virtual path components are passed to the handler as
+        positional arguments.
+        """
+        request = cherrypy.serving.request
+        app = request.app
+        root = app.root
+        fullpath = '/'.join([x for x in path.strip('/').split('/') if x])
+        nodeconf = {}
+
+        #TODO: Remember to update nodeconf's config with path appropriately
+        #Sort app config according to depth of path
+        #TODO: tools.staticdir.section ???
+        config = list(app.config.items())
+        config.sort(key = lambda x: x[0].count('/'))
+        for key, value in config:
+            if fullpath.startswith(key.strip('/')):
+                nodeconf.update(value)
+        request.config = nodeconf
+
+        for handler in self.handlers:
+            match = handler[0].match(fullpath)
+            if match is not None:
+                print('HEY', nodeconf)
+                #Dispatch!
+                return (handler[1], match.groupdict())
+        return (None, {})
+