diff --git a/corker/app.py b/corker/app.py index 6744a41..33fb25d 100644 --- a/corker/app.py +++ b/corker/app.py @@ -5,9 +5,14 @@ from routes.util import URLGenerator from webob import exc from webob.dec import wsgify +from webob.response import Response + +from corker.controller import BaseController + log = logging.getLogger(__name__) + class Application(object): """Give it a mapper, and it will return a wsgi app that gets routes via the mapper and executes them.""" @@ -21,9 +26,29 @@ def __call__(self, req): results = self.map.routematch(environ=req.environ) if not results: return exc.HTTPNotFound() + match, route = results link = URLGenerator(self.map, req.environ) + + if route.redirect: + # Taken from the routes middleware module + route_name = '_redirect_%s' % id(route) + location = link(route_name, **match) + + # Build the response manually so we don't have to try to map the + # route status to a specific webob exception + redirect_response = Response(status=route.redirect_status) + redirect_response.location = location + + return redirect_response + + match_controller = match.get('controller', None) + + if not callable(match_controller): + log.error('Unsupported route match: %s', match) + return exc.HTTPNotFound() + req.urlvars = ((), match) req.link = link - controller = match['controller'](req, **self.config) + controller = match_controller(req, **self.config) return controller() diff --git a/corker/controller.py b/corker/controller.py index cc37c6c..d8976e2 100644 --- a/corker/controller.py +++ b/corker/controller.py @@ -44,10 +44,8 @@ def setup_routes(cls, mapper, prefix='/', config={}): for route in attr._route: (args, kw) = route kw['action'] = attr_name - print("Map:", args, kw) m.connect(*args, **kw) - def __init__(self, request, **config): self.request = request for name, value in config.items(): diff --git a/corker/tests/test_main.py b/corker/tests/test_main.py index a40560c..a4dc366 100644 --- a/corker/tests/test_main.py +++ b/corker/tests/test_main.py @@ -111,3 +111,42 @@ def view(self, request, item): ret = app.get('/view/4') eq_(ret.body, b"Hi view 4!\n{'bdb': 5}\n4") + + +def test_redirect(): + mapper = Mapper() + mapper.redirect('/foo', '/bar', + _redirect_code="301 Moved Permanently") + + test_app = Application(mapper) + + app = TestApp(test_app) + + response = app.get('/foo') + + eq_(response.status, '301 Moved Permanently') + eq_(response.location, 'http://localhost/bar') + + +def test_bad_route(): + mapper = Mapper() + + mapper.connect('foo', '/foo') + + test_app = Application(mapper) + + app = TestApp(test_app) + + app.get('/foo', status=404) + + +def test_not_found(): + mapper = Mapper() + + mapper.connect('foo', '/foo') + + test_app = Application(mapper) + + app = TestApp(test_app) + + app.get('/bar', status=404)