M
M
Mariik2016-03-21 21:02:09
Python
Mariik, 2016-03-21 21:02:09

How to use a class method instead of a function in the Bottle microframework?

In general, what I want is to substitute the route decorator

@route('/hello')
test.test_method()

not a function, but a method call on a class object. For a bit of code example:
from bottle import route, run

class test():

    def g_test(self):
        return "<h1> Hello from test method! </h1>"

t = test()

@route('/test')
t.g_test()

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

But here I get a syntactic error
Ok, if I decorate the method itself:
from bottle import route, run, template

class test():
    @route('/hello')
    def getRes(self=None):
        return "<h1> Hello from test method! </h1>"

t = test()

run(host='localhost', port=8080,debug=True)

Everything will work, but Self is not defined, and without it there is no point ... Can this situation not be corrected?
I personally see only 2 options and both are "curves"
1 - Expand the decorator:
app.route('/', method='GET', callback=t.getRes())
2 - Wrap the method call in a function
@route('/test')
def view():
    t = test()
    return t.getRes()

Is there a normal way to use class methods?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Kobyshev, 2016-03-21
@yokotoka

What's the problem with doing

t = test()
@route('/test')
def test():
    return t.getRes()

?
With method decoration - you just need to write an intermediate decorator that uses the route decorator inside and does everything as it should, incl. throws self.
By the way, why bottle and not flask? He himself somehow used the first one, but then he realized that he had no advantages over the second one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question