Flask和自定义装饰器的更改顺序破坏了自定义装饰器

问题描述 投票:0回答:1

我为所有HTTP调用都做了一个日志装饰器:

def log_http_call(flask_request_getter: typing.Callable[[], flask.Request]):
    def arg_wrapper(wrapped_function):
        @wraps(wrapped_function)
        def wrapper(*args, **kwargs):
            flask_request: flask.Request = flask_request_getter()
            print(f'HTTP Method {flask_request.method}: {flask_request.path}')
            return wrapped_function(*args, **kwargs)    
        return wrapper    
    return arg_wrapper


@app.route('/api/all', methods=['GET'])
@log_http_call(lambda: flask.request)
def get_all():
    return "Here you go"


@app.route('/api/<int:_id>/<string:name>', methods=['GET'])
@log_http_call(lambda: flask.request)
def get_one(_id, name):
    return f"{name}'s ID is {_id}"

以这种方式工作,但是如果我将装饰器的顺序颠倒为例如:

@log_http_call(lambda: flask.request)
@app.route('/api/all', methods=['GET'])
def get_all():
    return "Here you go"

不再工作。

由于我代码的其他使用者可能以不同的顺序放置这些装饰器,因此我想确保它们以任何一种方式工作。

如何使它按任何顺序工作?

python python-3.x flask python-decorators
1个回答
0
投票
[您不能:装饰器将函数包装,将多个装饰器将函数包装在函数中。更具体地说:Decorator execution order
© www.soinside.com 2019 - 2024. All rights reserved.