How can a Flask decorator have arguments?

后端 未结 1 622
温柔的废话
温柔的废话 2021-02-13 15:54

I implemented a decorator in the same way as here How to make a python decorator function in Flask with arguments (for authorization) but problem still unsolved...

I hav

1条回答
  •  别跟我提以往
    2021-02-13 16:13

    Decorators are executed at import time, they're essentially syntactic sugar:

    @foo(bar)
    def baz():
        return 'w00t!'
    

    is equivalent to

    def baz():
       return 'w00t!'
    baz = foo(bar)(baz)
    

    So in the example above variable bar must exist in the global scope of this module before it is passed to the decorator as argument. That's what the error you've got tells you.


    Update

    Based on the discussion below, the code in the question should intercept the value passed to view function and do something with it. Here's an example that demonstrates it:

    from functools import wraps
    from flask import Flask, abort
    
    app = Flask(__name__)
    
    def foobar(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            value = kwargs['value']
            # Do something with value...
            if value == 'foobar':
                abort(400)
            return fn(*args, **kwargs)
        return decorated_view
    
    @app.route('/')
    @foobar
    def view(value):
        return value
    

    0 讨论(0)
提交回复
热议问题