Throoze
Throoze

Reputation: 4038

django.utils.thread_support in django 1.5

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"

EDIT:

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!

Upvotes: 6

Views: 1207

Answers (2)

coredumperror
coredumperror

Reputation: 9100

For future googlers, there is now a python package that provides a much more robust version of this middleware: django-crequest

Upvotes: 1

Dan Gayle
Dan Gayle

Reputation: 2357

Replace

from django.utils.thread_support import currentThread
currentThread()

with

from threading import current_thread
current_thread()

Upvotes: 2

Related Questions