Flask:属性值无

2024-09-27 00:12:18 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的代码块:
下面一个是覆盖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,我该怎么办


Tags: namefromimportselfnoneconfigappflask
1条回答
网友
1楼 · 发布于 2024-09-27 00:12:18

您可以使用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

相关问题 更多 >

    热门问题