python-如何在 Flask 中设置全局变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35309042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python-How to set global variables in Flask?
提问by jinglei
I'm working on a Flask
project and I want to have my index load more contents when scroll.
I want to set a global variable to save how many times have the page loaded.
My project is structured as :
我正在做一个Flask
项目,我想让我的索引在滚动时加载更多内容。我想设置一个全局变量来保存页面加载的次数。我的项目结构如下:
├──run.py
└──app
├──templates
├──_init_.py
├──views.py
└──models.py
At first, I declare the global variable in _init_.py
:
首先,我声明了全局变量_init_.py
:
global index_add_counter
and Pycharm warned Global variable 'index_add_counter' is undefined at the module level
和 Pycharm 警告 Global variable 'index_add_counter' is undefined at the module level
In views.py
:
在views.py
:
from app import app,db,index_add_counter
and there's ImportError: cannot import name index_add_counter
还有 ImportError: cannot import name index_add_counter
I've also referenced global-variable-and-python-flaskBut I don't have a main() function. What is the right way to set global variable in Flask?
我还引用了global-variable-and-python-flask但我没有 main() 函数。在 Flask 中设置全局变量的正确方法是什么?
采纳答案by Salva
With:
和:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and notcreate a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
您不是在定义,只是在声明,所以这就像在说别处有一个全局index_add_counter
变量,而不是创建一个名为index_add_counter
. 由于您的名字不存在,Python 告诉您它无法导入该名称。因此,您只需删除global
关键字并初始化您的变量:
index_add_counter = 0
Now you can import it with:
现在您可以使用以下命令导入它:
from app import index_add_counter
The construction:
那个工程:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
在模块的定义中使用以强制解释器在模块的范围内查找该名称,而不是在定义一中:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)