[英]How to access app.config from blueprint outside of request (Flask, pluggable views)
我希望能够从 Pluggable View 类访问 app.config
我有什么:flask 应用程序、可插入视图、蓝图
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 个月后),而不是你的烧瓶代码或烧瓶。
当您直接在类中设置字段时,您正在设置类的静态字段。 当一个类被初始化时,它“继承”了静态字段。 但它们永远不会被重新计算。 要解决未设置 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
,因为这将初始化一个实例变量。
但是你仍然不能像flask那样改变装饰器。 原因是因为它不会在请求时转换装饰器,它会在您在可插入视图上调用 .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
如您所见,它在转换为视图时专门访问静态装饰器列表。 所以你在构造函数中对它做什么并不重要,它已经创建了它们。
如果您需要此功能(我不知道为什么您首先需要它?)那么最好在您自己的装饰器中实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.