I'm trying to implement a django custom middleware that gives me access to the request
object wherever I am in my project, based in the one suggested here. That article was written a long time ago, and django 1.5 does not have the library thread_support
where it was back then. What alternative should I use to accomplish a thread safe local store to store the request object? This is the code in the custom middleware:
from django.utils.thread_support import currentThread
_requests = {}
def get_request():
return _requests[currentThread()]
class GlobalRequestMiddleware(object):
def process_request(self, request):
_requests[currentThread()] = request
And, of course, it raises an exception:
ImproperlyConfigured: Error importing middleware myProject.middleware.global:
"No module named thread_support"
I found out a working fix:
from threading import local
_active = local()
def get_request():
return _active.request
class GlobalRequestMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
_active.request = request
return None
Now I have a question: Does it leads to a memory leak? what happens with _active
? is it cleaned when the request dies? Anyway, There's a valid answer already posted. I'm going to accept it but any other (better, if possible) solution would be very welcome! Thanks!
Replace
from django.utils.thread_support import currentThread
currentThread()
with
from threading import current_thread
current_thread()
For future googlers, there is now a python package that provides a much more robust version of this middleware: django-crequest
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With