pythonpython-decoratorsbottle

Adding Decorator to a bottle request within a class


I wanted to add a decorator function that wraps a bottle request decorated function within a class, I tried doing it using inspect but I am unable to see any changes done by the decorator when I am calling this request.

This is my code :

import inspect
from bottle import run, route, template, get, post, request, delete, redirect

def decorator_jwt(func):
    def authenticate_jwt(*args):
        if(Afunction()):
            func(*args)
        else:
            return False
    return authenticate_jwt

def decorator_for_class(cls):
    for name, method in inspect.getmembers(cls):
        if (not inspect.ismethod(method) and not inspect.isfunction(method)) or inspect.isbuiltin(method):
            continue
        print("Decorating function %s" % name)
        setattr(cls, name, decorator_jwt(method))
    return cls

@decorator_for_class
class python_functions:
    @route('/')
    def show_index():
        #something0

    @get('/api/V1/something')
    def Reboot():
        #something

    @get('/api/V1/something2')
    def umountDevice():
        #something2

    @post('/api/V1/random/something3')
    def LogOut():
        #something3


Solution

  • The route decorator adds the callback function to the list of routes stored in the Bottle object of the current app, so applying your decorator_jwt decorator afterwards makes no difference to the callback functions already stored in the list.

    Instead, you can iterate through the routes stored in the Bottle object of the current app to alter the stored callbacks with the decorator_jwt decorator applied:

    from bottle import app
    
    def decorator_for_class(cls):
        callbacks = {
            func for func in inspect.getmembers(cls)
            if inspect.isfunction(func) and not inspect.isbuiltin(func)
        }
        for route in app().routes:
            if route.callback in callbacks:
                route.callback = decorator_jwt(route.callback)
        return cls