注册后,从烧瓶蓝图中返回全局变量

时间:2019-03-13 15:03:56

标签: python python-3.x flask

我正在尝试检索一个变量及其包含的内容,该变量是在“应用程序首次请求之前”创建的。是的,我很想将代码复制并粘贴到其他地方,并得到我要构建的内容,但我知道这样做并不雅致且有异味。因此变量必须仍然存在于某个地方,问题只是在哪里以及如何将其取回?

这是文件:

homepage.py

from flask import Blueprint

bp_home = Blueprint("home", __name__)

sharedvariable = None

def do_some_stuff():
    global shared_variable
    sharedvariable = 6

bp_home.before_app_first_request(do_some_stuff)

@bp_home.route("/home", methods=['GET'])
def home():
    return "There are {} dogs.".format(sharedvariable)

__ init __。py

from flask import Flask
from homepage import bp_home

app = Flask(__name__)
app.register_blueprint(bp_home)

然后在另一个脚本中-不会在此处复制,导入了应用,并且app.run在最后一行。

我正在研究一个新脚本:

mynewscript.py

from homepage import sharedvariable

# (details omitted)
print("sharedvariable is", sharedvariable)

现在,最后一张打印了:

sharedvariable is None

因此我意识到它是直接从脚本导入的,而没有运行do_some_stuff()函数。

我试图通过向homepage.py添加一些行来检索sharedvariable:

from flask import g                          # new line

def do_some_stuff():
    global shared_variable
    sharedvariable = 6
    g.sharedvariable = sharedvariable         # new line

但是当我试图在mynewscript.py中找回它时:

from flask import g

print("sharedvariable is", g.sharedvariable)

它说:

AttributeError: '_AppCtxGlobals' object has no attribute 'sharedvariable'

我的想法不多了。

我猜想当导入bp_home时,隐藏在其中的某个地方就是sharedvariable。无论如何,bp_home包含许多属性和方法,例如add_app_template_filteradd_app_template_globalapp_context_processor,还有大约十五个左右。

有人知道如何将可能在register_blueprint命令中创建的全局变量导入到新脚本中吗?宁愿回收并继续使用它,而不是在newscript中重新创建它。 (实际上是一个类实例,而不是6)。

更新: 我尝试this solution在文件之间共享全局变量,但是没有用。因此,现在我正努力通过为我的脚本创建第二个“ sharedvariable”实例来完成这项工作。

0 个答案:

没有答案