小编典典

python-如何在Flask中设置全局变量?

flask

我正在一个Flask项目上,我想让我的索引在滚动时加载更多内容。我想设置一个全局变量来保存页面已加载多少次。我的项目结构如下:

├──run.py
└──app
   ├──templates
   ├──_init_.py
   ├──views.py
   └──models.py

首先,我在中声明全局变量_init_.py

global index_add_counter

皮查姆(Pycharm)警告 Global variable 'index_add_counter' is undefined at the module level

views.py

from app import app,db,index_add_counter

还有 ImportError: cannot import name index_add_counter

我也引用了global-variable-and-python-flask 但我没有main()函数。在Flask中设置全局变量的正确方法是什么?


阅读 4744

收藏
2020-04-07

共1个答案

小编典典

global index_add_counter

你没有在定义,只是在声明,所以就好像在说其他地方有一个全局index_add_counter变量,而不是 创建一个称为index_add_counter的全局变量。由于你的名字不存在,Python告诉你无法导入该名字。因此,你只需删除global关键字并初始化变量:

index_add_counter = 0

现在,你可以使用以下命令导入它:

from app import index_add_counter

那个工程:

global index_add_counter

用于模块的定义内,以强制解释器在模块的范围内而不是在定义范围内查找该名称:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)
2020-04-07