Permalink
Browse files

Added support for a default route using the bottle.default() decorator.

Thanks to Damian (babs et sntteam dot org) who suggested this feature.
  • Loading branch information...
1 parent 863527a commit 333ff169d86df55f4cf9a2a94258d504147fafd5 @defnull defnull committed Aug 20, 2009
Showing with 32 additions and 0 deletions.
  1. +16 −0 bottle.py
  2. +16 −0 test/test_routes.py
View
16 bottle.py
@@ -164,6 +164,7 @@ class Bottle(object):
def __init__(self, catchall=True, debug=False, optimize=False, autojson=True):
self.simple_routes = {}
self.regexp_routes = {}
+ self.default_route = None
self.error_handler = {}
self.optimize = optimize
self.debug = debug
@@ -186,6 +187,8 @@ def match_url(self, url, method='GET'):
if i > 0 and self.optimize and random.random() <= 0.001:
routes[i-1], routes[i] = routes[i], routes[i-1]
return (handler, match.groupdict())
+ if self.default_route:
+ return (self.default_route, {})
return (None, None)
def add_route(self, route, handler, method='GET', simple=False):
@@ -207,6 +210,16 @@ def wrapper(handler):
return handler
return wrapper
+ def set_default(self, handler):
+ self.default_route = handler
+
+ def default(self):
+ """ Decorator for request handler. Same as add_defroute( handler )."""
+ def wrapper(handler):
+ self.set_default(handler)
+ return handler
+ return wrapper
+
def set_error_handler(self, code, handler):
""" Adds a new error handler. """
code = int(code)
@@ -456,6 +469,9 @@ def route(url, **kargs):
""" Decorator for request handler. Same as add_route(url, handler, **kargs)."""
return default_app().route(url, **kargs)
+def default():
+ """ Decorator for request handler. Same as set_default(handler)."""
+ return default_app().default()
def error(code=500):
""" Decorator for error handler. Same as set_error_handler(code, handler)."""
View
16 test/test_routes.py
@@ -30,6 +30,22 @@ def test_dynamic(self):
self.assertEqual(None, app.match_url('/aa')[0])
self.assertEqual(repr({'a':'aa','b':'bb'}), repr(app.match_url('/aa/bb')[1]))
+ def test_default(self):
+ """ Routes: Decorator and default routes """
+ app = Bottle()
+ token = 'abc'
+ @app.route('/exists')
+ def test1():
+ return 'test1'
+ @app.default()
+ def test2():
+ return 'test2'
+ self.assertEqual(test1, app.match_url('/exists')[0])
+ self.assertNotEqual(test2, app.match_url('/exists')[0])
+ self.assertEqual(test2, app.match_url('/does_not_exist')[0])
+ self.assertNotEqual(test1, app.match_url('/does_not_exist')[0])
+
+
def test_syntax(self):
""" Routes: Syntax """
#self.assertEqual(r'^/(?P<bla>[^/]+)$', compile_route('/:bla').pattern)

0 comments on commit 333ff16

Please sign in to comment.