【问题标题】:How to access app.config from blueprint outside of request (Flask, pluggable views)如何在请求之外从蓝图访问 app.config(Flask,可插入视图)
【发布时间】:2020-03-04 22:09:07
【问题描述】:

我希望能够从 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 flask


    【解决方案1】:

    问题出在你的 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,因为这会初始化一个实例变量。

    但是你仍然不能像在烧瓶中那样改变装饰器。原因是它不会在请求时转换装饰器,当您在可插入视图上调用 .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
    

    如您所见,它在转换为视图时专门访问静态装饰器列表。所以不管你在构造函数中对它做什么,它已经创建了它们。

    如果你需要这个功能(我不知道你为什么首先需要它?)那么最好在你自己的装饰器中实现它。

    【讨论】:

      猜你喜欢
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多