Python decorator with Flask

前端 未结 2 1834
终归单人心
终归单人心 2021-01-12 04:37

I need to add a python decorator to Flask route functions, (basically I edited the code from here)

def requires_admin(f):
    def wrapper(f):
        @wraps(         


        
2条回答
  •  长发绾君心
    2021-01-12 05:10

    You have two wrapper functions where you only need one. Notice that each wrapper function takes one argument. This should be a clue as to what is happening.

    You have:

    def decorator(take_a_function):
        def wrapper1(take_a_function):
            def wrapper2(*takes_multiple_arguments):
               # do stuff
               return take_a_function(*takes_multiple_arguments)
    
            return wrapper2
        return wrapper1
    

    When you decorate a function with it:

    @decorator
    def my_function(*takes_multiple_arguments):
       pass
    

    This is equivalent to:

    def my_function(*takes_multiple_arguments):
       pass
    
    my_function = decorator(my_function)
    

    but doing decorator(my_function) returns wrapper1, which if you recall takes one argument, take_a_function. This is clearly not what you want. You want wrapper2 returned. As in your answer, the solution is to remove the outer wrapper(wrapper1):

    from functools import wraps
    
    def decorator(takes_a_function):
        @wraps(takes_a_function)
        def wrapper(*args, **kwargs):
            # logic here
            return takes_a_function(*args, **kwargs)
    
        return wrapper
    

提交回复
热议问题