Files
tryton/trytond/model/cacheable.py
T

62 lines
2.0 KiB
Python
Raw Normal View History

2008-09-15 00:22:07 +02:00
#This file is part of Tryton. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
from trytond.tools import Cache
2008-10-14 00:12:46 +02:00
from threading import Lock
import time
2007-12-10 01:04:13 +01:00
class Cacheable(object):
2010-02-18 18:50:35 +01:00
_name = None
2007-12-10 01:04:13 +01:00
def __init__(self):
super(Cacheable, self).__init__()
self._cache = {}
self._max_len = 1024
self._timeout = 3600
self._lock = Lock()
self._timestamp = None
Cache._cache_instance.append(self)
2007-12-10 01:04:13 +01:00
def add(self, cursor, key, value):
self._lock.acquire()
try:
self._cache.setdefault(cursor.dbname, {})
lower = None
if len(self._cache[cursor.dbname]) > self._max_len:
mintime = time.time() - self._timeout
for key2 in self._cache[cursor.dbname].keys():
last_time = self._cache[cursor.dbname][key2][1]
if mintime > last_time:
del self._cache[cursor.dbname][key2]
else:
if not lower or lower[1] > last_time:
lower = (key2, last_time)
if len(self._cache[cursor.dbname]) > self._max_len and lower:
del self._cache[cursor.dbname][lower[0]]
self._cache[cursor.dbname][key] = (value, time.time())
finally:
self._lock.release()
2007-12-10 01:04:13 +01:00
def invalidate(self, cursor, key):
self._lock.acquire()
try:
del self._cache[cursor.dbname][key]
finally:
self._lock.release()
2007-12-10 01:04:13 +01:00
def get(self, cursor, key):
2007-12-10 01:04:13 +01:00
try:
2008-09-10 17:19:43 +02:00
return self._cache[cursor.dbname][key][0]
2007-12-10 01:04:13 +01:00
except KeyError:
return None
def clear(self, cursor):
self._lock.acquire()
try:
self._cache.setdefault(cursor.dbname, {})
self._cache[cursor.dbname].clear()
Cache.reset(cursor.dbname, self._name)
finally:
self._lock.release()