Skip to content

Instantly share code, notes, and snippets.

@davidwtbuxton
Created May 24, 2012 11:04

Revisions

  1. davidwtbuxton created this gist May 24, 2012.
    53 changes: 53 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    # Demonstration of inspecting all the routes, including those on sub-apps,
    # from the default app instance.
    #
    # This should be run directly to print a list of route prefixes and the rules.
    # Tested with Python 2.7 and Bottle-dev. Patch here
    # https://github.com/davidwtbuxton/bottle/commit/ddd712ef252b06ecd0e957f8ac4e37b65ee79cae
    import bottle


    subapp = bottle.Bottle()

    @subapp.route('/subhello')
    def subhello():
    return 'Sub Hello World'


    @bottle.route('/hello')
    def hello():
    return 'Hello World'


    subapp2 = bottle.Bottle()
    @subapp2.route('/')
    def subhello2():
    return 'Sub Hello World 2'


    bottle.mount('/subapp/', subapp)
    bottle.mount('/one/two/three/', subapp2)


    def inspect_routes(app, prefix=''):
    """Yields mount prefix and route object for an app. Mount-points for sub-
    apps are inspected recursively, yielding their routes too.
    """
    wildcard = r'/:#.*#'

    for route in app.routes:
    cb = route.callback
    rule = route.rule

    # Only follow a route with the wildcard. Some mounted apps will have
    # a second route to re-direct the request URL with a trailing slash.
    if isinstance(cb, bottle.MountPoint) and rule.endswith(wildcard):
    prefix = prefix + rule[:rule.rfind(wildcard)]
    for sprefix, sroute in inspect_routes(cb.app, prefix):
    yield sprefix, sroute
    else:
    yield prefix, route


    for prefix, route in inspect_routes(bottle.default_app()):
    print prefix, route.rule