django 1.5中的django.utils.thread_support

问题描述 投票:5回答:2

我正在尝试实现一个django自定义中间件,它允许我访问request对象,无论我在我的项目中,基于the one suggested here。那篇文章是很久以前写的,django 1.5没有库那里的thread_support。我应该使用什么替代方法来完成一个线程安全的本地存储来存储请求对象?这是自定义中间件中的代码:

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

当然,它引发了一个例外:

ImproperlyConfigured: Error importing middleware myProject.middleware.global: 
"No module named thread_support"

编辑:

我发现了一个有效的方法:

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

现在我有一个问题:是否会导致内存泄漏? _active会发生什么?当请求死亡时它被清理了吗?无论如何,已经发布了一个有效的答案。我将接受它,但任何其他(更好的,如果可能的话)解决方案将非常受欢迎!谢谢!

python django thread-safety
2个回答
2
投票

更换

from django.utils.thread_support import currentThread
currentThread()

from threading import current_thread
current_thread()

1
投票

对于未来的googlers,现在有一个python包提供了这个中间件的更强大的版本:django-crequest

© www.soinside.com 2019 - 2024. All rights reserved.