本文介绍了python-如何在 Flask 中设置全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 :

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

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

At first, I declare the global variable in _init_.py:

global index_add_counter

和 Pycharm 警告 全局变量 'index_add_counter' 在模块级别未定义

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

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?

推荐答案

With:

global index_add_counter

你不是在定义,只是在声明,就像在说在别处有一个全局的 index_add_counter 变量而不是 创建一个全局调用 index_add_counter.由于您的名字不存在,Python 告诉您它无法导入该名称.因此,您只需删除 global 关键字并初始化您的变量:

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create 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 = 0

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

Now you can import it with:

from app import index_add_counter

结构:

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)

这篇关于python-如何在 Flask 中设置全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 15:36
查看更多