我希望能够从Pluggable View类访问app.config
我所拥有的:烧瓶应用程序,可插入视图,蓝图
from flask import current_app
# using pluggable views
class Router(MethodView):
# applying flask_login.login_required to all methods
# in the current class
decorators = [flask_login.login_required]
def get(self, *args, **kwargs):
pass
def post(self, *args, **kwargs):
pass
我想要什么:(这不起作用,因为没有应用程序/请求上下文,也没有设置current_app(
from flask import current_app
class Router(MethodView):
# this does not work
if current_app.config['LOGIN_REQUIRED']:
decorators = [flask_login.login_required]
def get(self, *args, **kwargs):
pass
def post(self, *args, **kwargs):
pass
问题出在您的python代码上(5个月后您可能会意识到(,而不是您的flask代码或flask。
当直接在类中设置字段时,就是在设置类的静态字段。当一个类被初始化时,它会"继承"静态字段。但它们从未被重新计算过。要解决current_app未设置的问题,您可以执行以下操作:
from flask import current_app
class Router(MethodView):
def __init__(self):
login_required = current_app.config['LOGIN_REQUIRED']
# other logic etc
def get(self, *args, **kwargs):
pass
def post(self, *args, **kwargs):
pass
如果你想让它在get和post中访问login_required
,你只需要在构造函数中设置self.login_required
,因为这会初始化一个实例变量。
但你仍然不能改变烧瓶中的装饰器。原因是它不在请求时转换decorator,而是在可插入视图上调用.as_view时转换它们。正如我们在源文件flask/views.py
:中看到的那样
class View(object):
...
...
@classmethod
def as_view(cls, name, *class_args, **class_kwargs):
...
...
if cls.decorators:
view.__name__ = name
view.__module__ = cls.__module__
for decorator in cls.decorators:
view = decorator(view)
...
...
return view
正如您所看到的,它在转换为视图时专门访问静态装饰器列表。因此,在构造函数中对它做什么并不重要,它已经创建了它们。
如果你需要这个功能(我不知道你为什么一开始就需要它?(,那么最好在你自己的装饰器中实现它。