CherryPy / cherrypy /

Diff from to


     return decorated
+def popargsHandler(handler, *args, **kwargs):
+    """This is a utility function designed to be mounted on a cherrypy object
+    to serve up a different handler based on a parameter in the url.  For
+    instance, if your application has multiple databases, each of which
+    have requests that are handled by a common DatabaseHandler class, but you
+    want the database ID to appear as the first part of the URL, you would
+    use popargsHandler as follows:
+    class DatabaseHandler:
+        def __init__(self, myDbName):
+            ...
+        @cherrypy.expose
+        def index(self):
+            ...
+    cherrypy.tree.mount(popargsHandler(DatabaseHandler, 'myDbName'))
+    This will make the URL '/blah/arg/klar' first create a DatabaseHandler
+    object initialized with the kwarg myDbName='blah'.  Then the cherrypy
+    default dispatcher would look for the property arg.klar in that 
+    DatabaseHandler object to handle the request.
+    You can also mount this class under another cherrypy object:
+    class Root:
+        user = popargsHandler(UserHandler, 'username')
+    This code will turn urls like '/user/blah/delete' into creating a 
+    UserHandler object with username='blah' to handle the 'delete' request.
+    Note that, like cherrypy.popargs(), vpath elements that do not exist
+    still try to execute the handler, but will not pass those kwargs not
+    existing in the path.  The caveat to this is that if no argument is passed,
+    popargsHandler() will not be executed, and any parent object's default()
+    method will be used instead.  That is, at least one of the arguments
+    specified in popargsHandler() must be passed in the URL for popargsHandler
+    to do anything.
+    """
+    class PopargsHandlerClass:
+        """Fake class whose only purpose is to proxy popargs"""
+        pass
+    cls = popargs(*args, handler=handler, **kwargs)(PopargsHandlerClass)
+    return cls()
 def url(path="", qs="", script_name=None, base=None, relative=None):
     """Create an absolute URL for the given path.