I’ve done some coding with Bottle. It’s really simple and fits my needs. However, I got stick when I tried to wrap the application into a class :
import bottle
app = bottle
class App():
def __init__(self,param):
self.param = param
# Doesn't work
@app.route("/1")
def index1(self):
return("I'm 1 | self.param = %s" % self.param)
# Doesn't work
@app.route("/2")
def index2(self):
return("I'm 2")
# Works fine
@app.route("/3")
def index3():
return("I'm 3")
Is it possible to use methods instead of functions in Bottle?
Your code does not work because you are trying to route to non-bound methods. Non-bound methods do not have a reference to
self, how could they, if instance ofApphas not been created?If you want to route to class methods, you first have to initialize your class and then
bottle.route()to methods on that object like so:If you want to stick routes definitions near the handlers, you can do something like this:
Don’t do the
bottle.route()part inApp.__init__(), because you won’t be able to create two instances ofAppclass.If you like the syntax of decorators more than setting attribute
index.route=, you can write a simple decorator: