Python-How to set global variables in Flask?

I am working on a Flask project and I want my index to load more content when scrolling. I want to set a global variable to save how many times the page loaded. My project is structured as:

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

First, I declare a global variable in _init_.py :

 global index_add_counter 

and Pycharm warned Global variable 'index_add_counter' is undefined at the module level

In views.py :

 from app import app,db,index_add_counter 

and there ImportError: cannot import name index_add_counter

I also refer to global-variable-and-python-flask But I don't have a main () function. What is the correct way to set a global variable in Flask?

+6
source share
2 answers

WITH

 global index_add_counter 

You do not define, just declare that you want to say that there is a global variable index_add_counter elsewhere , and not create a global name index_add_counter . As you do not call, Python tells you that it cannot import this name. Therefore, you just need to remove the global and initialize your variable:

 index_add_counter = 0 

Now you can import it with:

 from app import index_add_counter 

Design:

 global index_add_counter 

used inside module definitions to force the interpreter to look for this name in the module area, and not in the definition:

 index_add_counter = 0 def test(): global index_add_counter # means: in this scope, use the global name print(index_add_counter) 
+8
source

The best place for global data in flask applications is the flask.g object, which is described here: http://flask.pocoo.org/docs/0.10/api/#flask.g

+3
source

All Articles