45

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

At first, I declare the 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's ImportError: cannot import name index_add_counter

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

Community
  • 1
  • 1
jinglei
  • 3,269
  • 11
  • 27
  • 46
  • 4
    Better place for global data in flask applications is the `flask.g` object, which is described here: http://flask.pocoo.org/docs/api/#flask.g – xscratt Feb 10 '16 at 08:01

1 Answers1

54

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 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

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)
Salva
  • 6,507
  • 1
  • 26
  • 25
  • 42
    Please note: While this makes sense for python requests, it might not make sense for Flask apps which can run in threads and workers. Defining a global like this might cause unexpected results when used in projection and you would be better off using a persistent data storage system like memcache or some other database. Depending on your use case this may or may not make sense. – BenDog Apr 10 '19 at 07:51
  • @BenDog Your comment makes sense. What's the right way to do it? – Tarik Sep 20 '20 at 13:14
  • 1
    Check this answer by @davidism on how to address several common scenarios where you need globals: https://stackoverflow.com/questions/32815451/are-global-variables-thread-safe-in-flask-how-do-i-share-data-between-requests – Salva Sep 23 '20 at 12:13