AgDude
AgDude

Reputation: 1185

Django view alter global variable

My django app contains a loop, which is launched by the following code in urls.py:

def start_serial():
    rfmon = threading.Thread(target=rf_clicker.RFMonitor().run)
    rfmon.daemon = True
    rfmon.start()

start_serial()

The loop inside this subthread references a global variable defined in global_vars.py. I would like to change to value of this variable in a view, but it doesn't seem to work.

from views.py:

import global_vars

def my_view(request):
    global_vars.myvar = 2
    return httpResponse...

How can a let the function inside the loop know that this view has been called?

The loop listens for a signal from a remote, and based on button presses may save data to the database. There are several views in the web interface, which change the settings for the remotes. While these settings are being changed the state inside the loop needs to be such that data will not be saved.

Upvotes: 0

Views: 722

Answers (2)

vkryachko
vkryachko

Reputation: 416

I agree with Ignacio Vazquez-Abrams, don't use globals. Especially in your use case. The problem with this approach is that, when you deploy your app to a wsgi container or what have you, you will have multiple instances of your app running in different processes, so changing a global variable in one process won't change it in others.

And I would also not recommend using threads. If you need a long running process that handles tasks asynchronously(which seems to be the case), consider looking at Celery( http://celeryproject.org/). It's really good at it.

Upvotes: 2

Keith Schoenefeld
Keith Schoenefeld

Reputation: 128

I will admit to having no experience leveraging them, but if you haven't looked at Django's signaling capabilities, it seems like they would be a prime candidate for this kind of activity (and more appropriate than global variables).

https://docs.djangoproject.com/en/dev/ref/signals/

Upvotes: 1

Related Questions