Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-How to set global variables in Flask? [duplicate]

Tags:

python

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 

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?

like image 929
jinglei Avatar asked Feb 10 '16 07:02

jinglei


People also ask

Can you have global variables in flask?

To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request.

Can 2 global variable have same name?

It is usually not a good programming practice to give different variables the same names. If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.

Are global variables thread safe in flask?

Global variables are still not thread safe because there's still no protection against most race conditions. You can still have a scenario where one worker gets a value, yields, another modifies it, yields, then the first worker also modifies it.


1 Answers

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) 
like image 131
Salva Avatar answered Sep 30 '22 02:09

Salva