【问题标题】:Python/Flask nested decorator with parameter带参数的 Python/Flask 嵌套装饰器
【发布时间】:2020-01-15 16:56:58
【问题描述】:

我正在尝试包装为烧瓶 (Flask-Kerberos) 制作的身份验证装饰器。我需要将参数传递给包装器,但我似乎不知道该怎么做。

原始工作代码:

#main.py:
@app.route("/")
@requires_authentication
def index(user):
    return render_template('index.html', user=user)

代码无效,但说明了我正在尝试做的事情:

#main.py
from auth import customauth
@app.route("/")
@customauth(config)
def index(user):
    return render_template('index.html', user=user)
#auth.py
def customauth(*args, **kwargs): 
    @requires_authentication
    def inner(func):
        print(config)
        return func
    return inner

【问题讨论】:

    标签: python flask python-decorators


    【解决方案1】:
    def customauth(config):
        def decorator(func):
            @requires_authentication
            def wrapper(*args, **kwargs):
                print(config)
                return func(*args, **kwargs)
    
            return wrapper
    
        return decorator
    

    如果您查找有关带参数的装饰器的教程,这基本上就是您将看到的内容。最外层的函数接受参数。内部是实际的装饰器,它接收被装饰的功能。最里面的是替换index的最终结果。为了理解它,想象一下打开函数调用。这段代码:

    @customauth(config)
    def index(user):
    

    相当于:

    @decorator  # for some specific config
    def index(user):
    

    相当于:

    @requires_authentication
    def wrapper(*args, **kwargs):
        print(config)
        return index(*args, **kwargs)  # func = index
    

    【讨论】:

    • 非常感谢!我花了一整天的时间试图围绕这些不同的例子。
    猜你喜欢
    • 2014-02-16
    • 1970-01-01
    • 2014-07-21
    • 2012-03-03
    • 2014-03-24
    • 2015-06-11
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多