Bottle framework and OOP, using method instead of function

后端 未结 5 1812
慢半拍i
慢半拍i 2020-12-04 10:46

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 bo         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 11:16

    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 of App has 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:

    import bottle        
    
    class App(object):
        def __init__(self,param):
            self.param   = param
    
        def index1(self):
            return("I'm 1 | self.param = %s" % self.param)
    
    myapp = App(param='some param')
    bottle.route("/1")(myapp.index1)
    

    If you want to stick routes definitions near the handlers, you can do something like this:

    def routeapp(obj):
        for kw in dir(app):
            attr = getattr(app, kw)
            if hasattr(attr, 'route'):
                bottle.route(attr.route)(attr)
    
    class App(object):
        def __init__(self, config):
            self.config = config
    
        def index(self):
            pass
        index.route = '/index/'
    
    app = App({'config':1})
    routeapp(app)
    

    Don't do the bottle.route() part in App.__init__(), because you won't be able to create two instances of App class.

    If you like the syntax of decorators more than setting attribute index.route=, you can write a simple decorator:

    def methodroute(route):
        def decorator(f):
            f.route = route
            return f
        return decorator
    
    class App(object):
        @methodroute('/index/')
        def index(self):
            pass
    

提交回复
热议问题