Django: Python global variables overlap, even for individual runs

I have a Django program (so Python) with a global variable:

g_variable = []

I use this several functions, where I also change the value:

my_function()
    global g_variable 
    g_variable.append(some_value)

This worked great until I started calling multiple program overlaps - in Django this means that I loaded the webpage several times quickly. I expected that the global variable would only be global in each individual run, but it is not. The values ​​that are added to g_variable in one pass can be seen in the next run.

For me, this means that now I have to pass this variable to all my functions:

my_function(non_g_variable)
    non_g_variable.append(some_value)
    return non_g_variable

called by

non_g_variable = my_function(non_g_variable)

? , , . .

+3
4

, , , . - :

class WebpageStructure(object):
    def __init__(self, html):
         # parse the html
         self.structure = self.parse(html)
    def contains_link(self):
         # figure it out using self.structure
         return ...

# in the view(s)
webpage = WebpageStructure(html_to_parse)
if webpage.contains_link():
    ...

:

  • , , g_variable [] . , ( Django, ?), . g_variable .

  • , . .

    1 2: Django manage.py runserver --nothreading . apache/mod_wsgi, , . , . , .

    , /.

  • , g_variable, . .

    /li >

:

import threading
threadlocal = threading.local()

def mydjangoview(request):
    # In your top-level view function, initialize the list
    threadlocal.g_variable = []
    # Then call the functions that use g_variable
    foo()
    bar()

    # ... and then I guess you probably return a response?
    return Response(...)

def foo():
    threadlocal.g_variable.append(some_value)

def bar():
    threadlocal.g_variable.append(some_other_value)

:

+3

, Python. , - .

, .

+2

, , , . . , , , .

So, yes, I would continue and implement the concept of receiving-modification-return or wait for someone to have a special β€œjangonical” solution to your problem.

+1
source

Your problems can be solved with cache - a simplified explanation of the cache - a global variable in the session.

0
source

All Articles