As at least one user here knows, I have a django-related package that I want to publish on PyPI, so I’ve been going the extra mile to ensure that it will work in environments other than our own. My concern is about a touchy topic: essentially, global variables. I converted my global variables into class attributes, but they are mutable and my goal is to make them thread-safe. I.e. I don’t want one user’s job that changes a global to affect another user’s job.
While I am open to considering alternate design suggestions that would avoid using what are essentially mutable global variables, I think I have a very strong case for this design pattern, and overall requirements that alternate design patterns (that would avoid globals) simply do not meet. So I would like to focus this discussion on how to (or if I can) use threading.local()
to make the usage of my globals/class-attributes safe. If you want to know why I have employed globals, you can read my stack post about it when I considered alternate design patterns and decided there was not another pattern that met my requirements.
My code does not explicitly use threads, nor do I intend for my code to create threads in the future. The threads I’m concerned about are the implicit ones (used either by apache or by django’s core code to service requests). Essentially, any concurrent executions with shared memory.
I don’t know much about threading.local()
, so I don’t know if it does what I imagine it does. All I want to do is something like this:
from threading import local
class MyModelSuperClass(Model):
data = local()
data.auto_update_mode = True
@classmethod
def set_auto_update_mode(cls, val=True):
cls.data.auto_update_mode = val
All of the models inherit from MyModelSuperClass
. MyModelSuperClass
overrides various Model methods, e.g. .save()
to perform auto-updates of various fields in each model, but sometimes, some code may want to change it’s save behavior or buffer the auto-updates and then execute them later.
Then in some 2 concurrently executed views on the django site, I want their data
to be independent of one another:
class EditView(...):
save_model_changes_with_default_autoupdate_behavior()
class LoadView(...):
MyModelSuperClass.set_auto_update_mode(False)
load_a_bunch_of_models_from_file_and_buffer_autoupdates()
# Restore the default
MyModelSuperClass.set_auto_update_mode()
perform_mass_auto_updates()
i.e. I don’t want the set in the LoadView
to change the behavior of saves in the EditView
if the apache server threads these executions with shared memory.
Does my example usage of local()
in MyModelSuperClass
to set MyModelSuperClass.data
protect me from the 2 executions interfering with one another?
Sorry if this is a dumb question. I’m not very familiar with threads in django or apache/nginx, etc. My only experience with threads and apache is with perl/mod_perl from a long time ago.