What is the best practice for writing a thread-safe context processor in Django?
Say, I want to pass some variables to templates, which are set in the corresponding views, and could be different for different view-template pairs.
One solution would be to manually pass each variable in the context:
return render_to_response('template.html', {'var1':var1,... 'var10':var10},
context_instance=RequestContext(request))
To keep it DRY, however, I would rather use a context processor. But I worry about thread safety as it seems to require a global store. Here is my solution using a context processor, which ties each variable to the request. Thanks for your comments and suggestions.
In context_processor.py
:
store = {}
def add_context(request, key, value):
if request not in store:
store[request] = {}
store[request][key] = value
return
def misc_context_processor(request):
return store.pop(request,{})
In views.py
:
import context_processor
def view(request):
...
if x == y:
context_processor.add_context(request,'var1','value1')
else:
context_processor.add_context(request,'var2','value2')
...
return render_to_response('template.html', {},
context_instance=RequestContext(request))
In settings.py
:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
...,
'appname.context_processor.misc_context_processor',
)