Python Django Global Variables

Python Django Global Variables

You mustn't declare global variables. Settings (constants) are OK if done right. But variables violate with shared-nothing architecture and might cause a lot of trouble. (best case they'll be inconsistent)

I would simply store those statistics in the cache. (Well, actually I would store them in the database but you made clear you believe it will have a negative impact on performance, so...)

The new incr() and decr() methods are especially suitable for counting. See docs for more info.

global variable not defined in django

Caution: Global variables violates maybe the most important principle of the programming, the encapsulation. Using them, will turn your code to a spaghetti. Don't use them. (Unless there is another way)

Here is what encapsulation means:

...Encapsulation refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object's components.

Source: Wikipedia

If you really want to use it, here is your problem: global keyword should be used in functions.

Let's try that way:

phone = ""
rand_num = 0

def phone_login(request):
global phone, rand_num
if request.method == 'POST':
...

def verify(request):
global phone, rand_num
if request.method == "POST":
...

Django application global variables in database best praxis

Decided to use a ready-made solution: django-extra-setting.

In apps setting define variables that will be storage in DB:

DB_VARIABLES = {'variable_name': ['text', 'default_value']}

Reads a variable from files after django project has been loaded



from settings import PROJECT_APPS
from extra_settings.models import Setting
from importlib import import_module
class CoreConfig(AppConfig):
def ready(self):
if (is_manage_py and is_runserver) or (not is_manage_py):
local_settings = import_module(f'path/{app_name}')
for app_name in PROJECT_APPS:
local_constants = local_settings.DB_VARIABLES if hasattr(local_settings, 'DB_VARIABLES') else False
if local_constants:
variables = {**variables, **{key: local_constants[key] for key in local_constants}}
for constant_name in local_constants:
if Setting.objects.filter(name=constant_name).count() == 0:
constant_values = local_constants[constant_name]
Setting(name=constant_name, value_type=constant_values[0], value=constant_values[1]).save()


What is the scope of global variables in the views.py?

Python as a language has the concept of scoping and global variables. The same applies here regardless of Django. See this example

x = 10

def first():
x = 20
print(x)

def second():
global x
print(x)
x = 30
print(x)

def third():
print(x)

first()
second()
third()

Output

20
10
30
30

In the first function x is redeclared with a new value and has no effect on the outer value. The function second prints the x just to verify that and then makes x global using the global keyword. Now, x is reinitialized in the outer scope, and function third confirms that.

In particular to your scenario, myglobalvar will only change for that particular request and the outer scope value will remain unchanged. However, if you use the global keyword.

global myglobalvar
myglobalvar = "different value"

inside thatOneLink, the value of myglobalvar will change for all the requests served by that process (even for all threads in that process) until you restart the process.

django how to use a variable globally

I think you can do this way:

simple_variable = initial_value 

def ViewName(request):
global simple_variable
simple_variable = value
...

def AnotherViewName(request):
global simple_variable

django global variable

Use sessions. This is exactly what they are designed for.

def foo(request):
num = request.session.get('num')
if num is None:
num = 1
request.session['num'] = num
return render(request,'foo.html')

def anotherfoo(request):
num = request.session.get('num')
# and so on, and so on

If the session has expired, or num did not exist in the session (was not set) then request.session.get('num') will return None. If you want to give num a default value, then you can do this request.session.get('num',5) - now if num wasn't set in the session, it will default to 5. Of course when you do that, you don't need the if num is None check.



Related Topics



Leave a reply



Submit