Django:如何记忆模型管理器方法?

2024-10-01 17:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个记下来的Django模型管理器方法,如下所示:

class GroupManager(models.Manager):
    def get_for_user(self, user):
        cache_key = 'groups_%s' % (user.id)
        if not hasattr(self, key):
            groups = get_groups_somehow()
            setattr(self, cache_key, groups)
        return getattr(self, cache_key)

但记忆值在请求/响应周期之后仍然存在;即在服务器重新启动之前,不会在后续请求中重新计算该值。这一定是因为管理器实例没有被销毁。在

那么,如何正确地记忆模型管理器方法呢?在


Tags: django方法记忆key模型selfcache管理器
2条回答

https://stackoverflow.com/a/1526245/287923的启发,但为了简化它,我实现了一个请求缓存,如下所示:

from threading import currentThread

caches = {}

class RequestCache(object):
    def set(self, key, value):
        cache_id = hash(currentThread())
        if caches.get(cache_id):
            caches[cache_id][key] = value
        else:
            caches[cache_id] = {key: value}

    def get(self, key):
        cache_id = hash(currentThread())
        cache = caches.get(cache_id)
        if cache:
            return cache.get(key)
        return None

class RequestCacheMiddleware(object):
    def process_response(self, request, response):
        cache_id = hash(currentThread())
        if caches.get(cache_id):
            del(caches[cache_id])
        return response

caches是缓存字典的字典,通过get&;set方法访问。在呈现响应之后,中间件将清除process_response方法中当前线程的缓存。在

它是这样使用的:

^{pr2}$

不会重新计算键值,因为您告诉它一旦该键存在就不要重新计算。如果要在后续调用中重新计算,请重新排序代码

class GroupManager(models.Manager):
    def get_for_user(self, user):
        cache_key = 'groups_%s' % (user.id)
        groups = get_groups_somehow()
        setattr(self, cache_key, groups)
        return getattr(self, cache_key)

如果您想在不重新计算的情况下获得缓存的值,只需在管理器上使用getattr和正确的键。在

相关问题 更多 >

    热门问题