Use a tween application instead of a catchall route.
authorChristophe de Vienne <christophe@unlish.com>
Wed, 06 Aug 2014 19:04:25 +0200
changeset 11496 500615e26063
parent 11495 f936708c6ea2
child 11497 855219da7c70
Use a tween application instead of a catchall route. Using a catchall route has some drawbacks. Especially, we have no mean to have a route that would match only if no other one does AND no view matches either. Said differently, our default handler cannot be plugged on the route level nor the view level, because it is has to be activated only if nothing else works in the pyramid application. Using a tween application allow to handle requests that raises a HTTPNotFound error, while having the pyramid error handler still active between our tween app and the outside world. Related to #4291173
pyramid_cubicweb/bwcompat.py
--- a/pyramid_cubicweb/bwcompat.py	Mon Aug 04 15:52:04 2014 +0200
+++ b/pyramid_cubicweb/bwcompat.py	Wed Aug 06 19:04:25 2014 +0200
@@ -1,4 +1,5 @@
 from pyramid import security
+from pyramid import tweens
 from pyramid.httpexceptions import HTTPSeeOther
 from pyramid import httpexceptions
 
@@ -105,8 +106,22 @@
         return request.response
 
 
+class TweenHandler(object):
+    def __init__(self, handler, registry):
+        self.handler = handler
+        self.cwhandler = registry['cubicweb.handler']
+
+    def __call__(self, request):
+        try:
+            response = self.handler(request)
+        except httpexceptions.HTTPNotFound:
+            response = self.cwhandler(request)
+        return response
+
+
 def includeme(config):
-    # Set up a defaut route to handle non-catched urls.
+    # Set up a tween app that will handle the request if the main application
+    # raises a HTTPNotFound exception.
     # This is to keep legacy compatibility for cubes that makes use of the
     # cubicweb controllers.
     cwconfig = config.registry['cubicweb.config']
@@ -114,10 +129,10 @@
     cwappli = CubicWebPublisher(
         repository, cwconfig,
         session_handler_fact=PyramidSessionHandler)
-    handler = CubicWebPyramidHandler(cwappli)
+    cwhandler = CubicWebPyramidHandler(cwappli)
 
     config.registry['cubicweb.appli'] = cwappli
-    config.registry['cubicweb.handler'] = handler
+    config.registry['cubicweb.handler'] = cwhandler
 
-    config.add_route('catchall', pattern='*path')
-    config.add_view(handler, route_name='catchall')
+    config.add_tween(
+        'pyramid_cubicweb.bwcompat.TweenHandler', under=tweens.EXCVIEW)