python-如何在Flask中设置全局变量? [重复]

问题描述 投票:0回答:1

我正在开发一个

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 中设置全局变量的正确方法是什么?

python flask
1个回答
54
投票

与:

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)
    
© www.soinside.com 2019 - 2024. All rights reserved.