Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 906
Throoze Avatar asked Sep 04 '13 04:09

Throoze


2 Answers

Replace

from django.utils.thread_support import currentThread
currentThread()

with

from threading import current_thread
current_thread()
like image 103
Dan Gayle Avatar answered Oct 13 '22 00:10

Dan Gayle


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

like image 25
coredumperror Avatar answered Oct 12 '22 22:10

coredumperror