inker
inker

Reputation: 117

How does python bottle framework install routing handler through decorator?

An example for installing routing handler under python bottle framework is as follow:

from bottle import Bottle, run
app = Bottle()

@app.route('/hello')
def hello():
    return "Hello World!"

run(app, host='localhost', port=8080)

The above code will route "localhost:8080/hello" to page showing "Hello World!"(handled by function hello). I wonder how this install process can be done? How can the framework know function "hello" uses "app.route" as its decorator, and thus dispatch the incoming request to that function?

Upvotes: 1

Views: 680

Answers (1)

vaultah
vaultah

Reputation: 46533

A name of a function doesn't mean anything to Bottle, but only as long as you provide a path (or paths) to route decorator.

Arguments to Route's constructor include callback and rule, where callback is your function and rule is a path string.

If one or more paths were provided, the Bottle will simply create a Route instance for every path.

Function name only comes into play, if you don't provide a single path to route. Bottle will then generate possible paths from a function's signature (see the source for yieldroutes) and create a Route instance for each one of them.

The related part from Bottle.route's source:

for rule in makelist(path) or yieldroutes(callback):
    for verb in makelist(method):
        verb = verb.upper()
        route = Route(self, rule, verb, callback, name=name,
                      plugins=plugins, skiplist=skiplist, **config)
        self.add_route(route)

Upvotes: 2

Related Questions