【问题标题】:Flask: Attribute Value NoneFlask:属性值无
【发布时间】:2021-03-21 13:55:37
【问题描述】:

这是我的代码块:
下面的一个是覆盖 Flask Blueprint 并添加属性 config 来复制应用程序的配置。

# Overriding Flask Blueprint
from flask import Blueprint


class CustomBlueprint(Blueprint):

    def __init__(self, name, import_name):
        super().__init__(name, import_name)
        self.config = None
        self.guard = None

    def register(self, app, options, first_registration=False):
        self.config = app.config
        self.guard = app.guard
        print(self.guard) # Works Fine
        print(self.config) # Works Fine
        super(CustomBlueprint, self).register(app, options, first_registration)

下面一个正在使用该类。

from src.SHARED.overriden.blueprint import CustomBlueprint
from .guard import module_guard

example = CustomBlueprint('EXAMPLE', __name__)
print(example.config) # Here is the problem: It prints None


@example.route('/')
@module_guard
def hello_example():
    return "Example is Working !!"

我也尝试了另一种方法,使用 @property、getter 和 setter。但这会产生错误,
属性错误:无法添加属性

我想访问/打印app.config,我应该怎么做??

【问题讨论】:

    标签: python flask


    【解决方案1】:

    你的 app.py 中需要 app.app_context().push()

    【讨论】:

      【解决方案2】:

      您可以使用current_app.config 在您的蓝图中访问app.config

      from flask import Blueprint, current_app
      from .guard import module_guard
      
      example = Blueprint('EXAMPLE', __name__)
      # Want to access current_app here e.g print(current_app.config)
      
      @example.route('/')
      @module_guard
      def hello_example():
          return '{}'.format(current_app.config.get('ENV'))
      
      

      https://flask.palletsprojects.com/en/1.1.x/api/#flask.current_app

      【讨论】:

      • 不工作的兄弟!错误:“脱离上下文”即使我参考了 current_app 的文档并相应地做了我的意图是要知道......为什么它给出 None ??
      • 您只能在推送应用程序上下文时访问current_app,例如在请求期间,您能否发布一个您尝试对配置执行的操作的示例?
      • 是的,我知道它在路由/端点的函数内工作正常,但我想在请求函数之外访问它,例如``` from flask import Blueprint, current_app from .guard import module_guard example = Blueprint('EXAMPLE', name) # 比如说,我想在这里打印 app.config 例如 print(current_app.config ) # Will Throw Out of Context Her @example.route('/') @module_guard def hello_example(): return '{}'.format(current_app.config.get('ENV')) # 在这里,它可以正常工作```
      猜你喜欢
      • 2018-01-13
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      相关资源
      最近更新 更多