Bottle framework and OOP, using method instead of function

后端 未结 5 1805
慢半拍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:13

    I took @Skirmantas answer and modified it a bit to allow for keyword arguments in the decorator, like method, skip, etc:

    def routemethod(route, **kwargs):
        def decorator(f):
            f.route = route
            for arg in kwargs:
                setattr(f, arg, kwargs[arg])
            return f
        return decorator
    
    def routeapp(obj):
        for kw in dir(obj):
            attr = getattr(obj, kw)
            if hasattr(attr, "route"):
                if hasattr(attr, "method"):
                    method = getattr(attr, "method")
                else:
                    method = "GET"
                if hasattr(attr, "callback"):
                    callback = getattr(attr, "callback")
                else:
                    callback = None
                if hasattr(attr, "name"):
                    name = getattr(attr, "name")
                else:
                    name = None
                if hasattr(attr, "apply"):
                    aply = getattr(attr, "apply")
                else:
                    aply = None
                if hasattr(attr, "skip"):
                    skip = getattr(attr, "skip")
                else:
                    skip = None
    
                bottle.route(attr.route, method, callback, name, aply, skip)(attr)
    

提交回复
热议问题