加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – django 1.5中的django.utils.thread_support

发布时间:2020-12-16 21:39:34 所属栏目:Python 来源:网络整理
导读:我正在尝试实现一个 django自定义中间件,它允许我访问请求对象,无论我在我的项目中的哪个位于 the one suggested here.那篇文章是很久以前写的,django 1.5没有库thread_support它回来了然后.我应该使用什么替代方法来完成一个线程安全的本地存储来存储请求对
我正在尝试实现一个 django自定义中间件,它允许我访问请求对象,无论我在我的项目中的哪个位于 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会发生什么?当请求死亡时它被清理了吗?无论如何,已经发布了一个有效的答案.我将接受它,但任何其他(更好的,如果可能的话)解决方案将非常受欢迎!谢谢!

解决方法

更换
from django.utils.thread_support import currentThread
currentThread()

from threading import current_thread
current_thread()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读