gpt4 book ai didi

python - 装饰Flask MethodView派生类中的方法

转载 作者:行者123 更新时间:2023-12-05 01:02:35 25 4
gpt4 key购买 nike

我认为我可以通过如下装饰 __enter__ 来要求所有派生 View 的登录:

from flask.views import MethodView
from flask.ext.login import login_required
class LoggedInView(MethodView):
@login_required
def __enter__(self):
pass

如果我添加一些日志记录,结果是没有输入 __enter__。同样,__exit__ 也不会发生。

这是怎么回事?

我可以修改样式来装饰一些其他功能,但是有必要在派生 View 中调用 super(),这样一开始就失去了这样做的意义。

除了继承 LoggedInView 之外,我如何在 View 中不做任何工作的情况下强制执行这种修饰?

最佳答案

要装饰 MethodView 实例的方法,您必须添加一个 decorators 类变量以及要调用的装饰器列表。见 documentation .

对于您的示例,它将是:

from flask.views import MethodView
from flask.ext.login import login_required

class LoggedInView(MethodView):
decorators = [login_required]

def get(self):
pass

def post(self):
pass

# ...

请注意,装饰器适用于所有定义的方法。

关于python - 装饰Flask MethodView派生类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32857960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com