Commits

Robert Brewer committed d985b13

New mount_point and url methods on cherrypy.tree.

Comments (0)

Files changed (2)

cherrypy/_cptree.py

                 cherrypy.config.update(updateMap=conf, baseurl=baseurl)
             else:
                 cherrypy.config.update(file=conf, baseurl=baseurl)
+    
+    def mount_point(self, path=None):
+        """The 'root path' of the app which governs the given path, or None.
+        
+        If path is None, cherrypy.request.object_path is used.
+        """
+        
+        if path is None:
+            try:
+                import cherrypy
+                path = cherrypy.request.object_path
+            except AttributeError:
+                return None
+        
+        while path:
+            if path in self.mount_points:
+                return path
+            
+            # Move one node up the tree and try again.
+            if path == "/":
+                break
+            path = path[:path.rfind("/")] or "/"
+        
+        return None
+    
+    def url(self, path, mount_point=None):
+        """Return 'path', prefixed with mount_point.
+        
+        If mount_point is None, cherrypy.request.object_path will be used
+        to find a mount point.
+        """
+        
+        if mount_point is None:
+            mount_point = self.mount_point()
+            if mount_point is None:
+                return path
+        
+        from cherrypy.lib import httptools
+        return httptools.urljoin(mount_point, path)
 

cherrypy/test/test_objectmapping.py

         return "index for dir2, path is:" + cherrypy.request.path
     index.exposed = True
     
-    def method(self):
-        return "method for dir2"
-    method.exposed = True
+    def mount_point(self):
+        return cherrypy.tree.mount_point()
+    mount_point.exposed = True
+    
+    def tree_url(self):
+        return cherrypy.tree.url("/extra")
+    tree_url.exposed = True
     
     def posparam(self, *vpath):
         return "/".join(vpath)
 class ObjectMappingTest(helper.CPWebCase):
     
     def testObjectMapping(self):
-        def run():
-            prefix = self.mount_point
+        for url in mount_points:
+            prefix = self.mount_point = url
             if prefix == "/":
                 prefix = ""
             
             # See ticket #393.
             self.getPage("/page%2Fname")
             self.assertBody("default:('page/name',)")
-        
-        for url in mount_points:
-            self.mount_point = url
-            run()
+            
+            self.getPage("/dir1/dir2/mount_point")
+            self.assertBody(url)
+            self.getPage("/dir1/dir2/tree_url")
+            self.assertBody(prefix + "/extra")
         
         self.mount_point = ""